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.UnstableApi;
23  import io.netty.util.internal.logging.InternalLogger;
24  import io.netty.util.internal.logging.InternalLoggerFactory;
25  
26  import java.io.Closeable;
27  import java.net.SocketAddress;
28  import java.util.IdentityHashMap;
29  import java.util.Map;
30  import java.util.concurrent.ConcurrentMap;
31  
32  /**
33   * Creates and manages {@link NameResolver}s so that each {@link EventExecutor} has its own resolver instance.
34   */
35  @UnstableApi
36  public abstract class AddressResolverGroup<T extends SocketAddress> implements Closeable {
37  
38      private static final InternalLogger logger = InternalLoggerFactory.getInstance(AddressResolverGroup.class);
39  
40      /**
41       * Note that we do not use a {@link ConcurrentMap} here because it is usually expensive to instantiate a resolver.
42       */
43      private final Map<EventExecutor, AddressResolver<T>> resolvers =
44              new IdentityHashMap<EventExecutor, AddressResolver<T>>();
45  
46      protected AddressResolverGroup() { }
47  
48      /**
49       * Returns the {@link AddressResolver} associated with the specified {@link EventExecutor}. If there's no associated
50       * resolved found, this method creates and returns a new resolver instance created by
51       * {@link #newResolver(EventExecutor)} so that the new resolver is reused on another
52       * {@link #getResolver(EventExecutor)} call with the same {@link EventExecutor}.
53       */
54      public AddressResolver<T> getResolver(final EventExecutor executor) {
55          if (executor == null) {
56              throw new NullPointerException("executor");
57          }
58  
59          if (executor.isShuttingDown()) {
60              throw new IllegalStateException("executor not accepting a task");
61          }
62  
63          AddressResolver<T> r;
64          synchronized (resolvers) {
65              r = resolvers.get(executor);
66              if (r == null) {
67                  final AddressResolver<T> newResolver;
68                  try {
69                      newResolver = newResolver(executor);
70                  } catch (Exception e) {
71                      throw new IllegalStateException("failed to create a new resolver", e);
72                  }
73  
74                  resolvers.put(executor, newResolver);
75                  executor.terminationFuture().addListener(new FutureListener<Object>() {
76                      @Override
77                      public void operationComplete(Future<Object> future) throws Exception {
78                          synchronized (resolvers) {
79                              resolvers.remove(executor);
80                          }
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 AddressResolver}.
94       */
95      protected abstract AddressResolver<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 AddressResolver<T>[] rArray;
104         synchronized (resolvers) {
105             rArray = (AddressResolver<T>[]) resolvers.values().toArray(new AddressResolver[resolvers.size()]);
106             resolvers.clear();
107         }
108 
109         for (AddressResolver<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 }