View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.resolver;
18  
19  import io.netty.util.concurrent.EventExecutor;
20  import io.netty.util.concurrent.Future;
21  import io.netty.util.concurrent.FutureListener;
22  import io.netty.util.internal.logging.InternalLogger;
23  import io.netty.util.internal.logging.InternalLoggerFactory;
24  
25  import java.io.Closeable;
26  import java.net.SocketAddress;
27  import java.util.IdentityHashMap;
28  import java.util.Map;
29  import java.util.concurrent.ConcurrentMap;
30  
31  /**
32   * Creates and manages {@link NameResolver}s so that each {@link EventExecutor} has its own resolver instance.
33   */
34  public abstract class NameResolverGroup<T extends SocketAddress> implements Closeable {
35  
36      private static final InternalLogger logger = InternalLoggerFactory.getInstance(NameResolverGroup.class);
37  
38      /**
39       * Note that we do not use a {@link ConcurrentMap} here because it is usually expensive to instantiate a resolver.
40       */
41      private final Map<EventExecutor, NameResolver<T>> resolvers =
42              new IdentityHashMap<EventExecutor, NameResolver<T>>();
43  
44      protected NameResolverGroup() { }
45  
46      /**
47       * Returns the {@link NameResolver} associated with the specified {@link EventExecutor}.  If there's no associated
48       * resolved found, this method creates and returns a new resolver instance created by
49       * {@link #newResolver(EventExecutor)} so that the new resolver is reused on another
50       * {@link #getResolver(EventExecutor)} call with the same {@link EventExecutor}.
51       */
52      public NameResolver<T> getResolver(EventExecutor executor) {
53          if (executor == null) {
54              throw new NullPointerException("executor");
55          }
56  
57          if (executor.isShuttingDown()) {
58              throw new IllegalStateException("executor not accepting a task");
59          }
60  
61          return getResolver0(executor.unwrap());
62      }
63  
64      private NameResolver<T> getResolver0(final EventExecutor executor) {
65          NameResolver<T> r;
66          synchronized (resolvers) {
67              r = resolvers.get(executor);
68              if (r == null) {
69                  final NameResolver<T> newResolver;
70                  try {
71                      newResolver = newResolver(executor);
72                  } catch (Exception e) {
73                      throw new IllegalStateException("failed to create a new resolver", e);
74                  }
75  
76                  resolvers.put(executor, newResolver);
77                  executor.terminationFuture().addListener(new FutureListener<Object>() {
78                      @Override
79                      public void operationComplete(Future<Object> future) throws Exception {
80                          resolvers.remove(executor);
81                          newResolver.close();
82                      }
83                  });
84  
85                  r = newResolver;
86              }
87          }
88  
89          return r;
90      }
91  
92      /**
93       * Invoked by {@link #getResolver(EventExecutor)} to create a new {@link NameResolver}.
94       */
95      protected abstract NameResolver<T> newResolver(EventExecutor executor) throws Exception;
96  
97      /**
98       * Closes all {@link NameResolver}s created by this group.
99       */
100     @Override
101     @SuppressWarnings({ "unchecked", "SuspiciousToArrayCall" })
102     public void close() {
103         final NameResolver<T>[] rArray;
104         synchronized (resolvers) {
105             rArray = (NameResolver<T>[]) resolvers.values().toArray(new NameResolver[resolvers.size()]);
106             resolvers.clear();
107         }
108 
109         for (NameResolver<T> r: rArray) {
110             try {
111                 r.close();
112             } catch (Throwable t) {
113                 logger.warn("Failed to close a resolver:", t);
114             }
115         }
116     }
117 }