View Javadoc
1   /*
2    * Copyright 2015 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    *   https://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  package io.netty.channel.pool;
17  
18  import io.netty.util.concurrent.Future;
19  import io.netty.util.concurrent.GlobalEventExecutor;
20  import io.netty.util.concurrent.Promise;
21  import io.netty.util.internal.ReadOnlyIterator;
22  
23  import java.io.Closeable;
24  import java.util.Iterator;
25  import java.util.Map.Entry;
26  import java.util.concurrent.ConcurrentHashMap;
27  import java.util.concurrent.ConcurrentMap;
28  
29  import static io.netty.util.internal.ObjectUtil.checkNotNull;
30  
31  /**
32   * A skeletal {@link ChannelPoolMap} implementation. To find the right {@link ChannelPool}
33   * the {@link Object#hashCode()} and {@link Object#equals(Object)} is used.
34   */
35  public abstract class AbstractChannelPoolMap<K, P extends ChannelPool>
36          implements ChannelPoolMap<K, P>, Iterable<Entry<K, P>>, Closeable {
37      private final ConcurrentMap<K, P> map = new ConcurrentHashMap<>();
38  
39      @Override
40      public final P get(K key) {
41          P pool = map.get(checkNotNull(key, "key"));
42          if (pool == null) {
43              pool = newPool(key);
44              P old = map.putIfAbsent(key, pool);
45              if (old != null) {
46                  // We need to destroy the newly created pool as we not use it.
47                  poolCloseAsyncIfSupported(pool);
48                  pool = old;
49              }
50          }
51          return pool;
52      }
53      /**
54       * Remove the {@link ChannelPool} from this {@link AbstractChannelPoolMap}. Returns {@code true} if removed,
55       * {@code false} otherwise.
56       *
57       * If the removed pool extends {@link SimpleChannelPool} it will be closed asynchronously to avoid blocking in
58       * this method.
59       *
60       * Please note that {@code null} keys are not allowed.
61       */
62      public final boolean remove(K key) {
63          P pool =  map.remove(checkNotNull(key, "key"));
64          if (pool != null) {
65              poolCloseAsyncIfSupported(pool);
66              return true;
67          }
68          return false;
69      }
70  
71      /**
72       * Remove the {@link ChannelPool} from this {@link AbstractChannelPoolMap}. Returns a future that comletes with a
73       * {@code true} result if the pool has been removed by this call, otherwise the result is {@code false}.
74       *
75       * If the removed pool extends {@link SimpleChannelPool} it will be closed asynchronously to avoid blocking in
76       * this method. The returned future will be completed once this asynchronous pool close operation completes.
77       */
78      private Future<Boolean> removeAsyncIfSupported(K key) {
79          P pool =  map.remove(checkNotNull(key, "key"));
80          if (pool != null) {
81              final Promise<Boolean> removePromise = GlobalEventExecutor.INSTANCE.newPromise();
82              poolCloseAsyncIfSupported(pool).addListener(future -> {
83                  if (future.isSuccess()) {
84                      removePromise.setSuccess(Boolean.TRUE);
85                  } else {
86                      removePromise.setFailure(future.cause());
87                  }
88              });
89              return removePromise;
90          }
91          return GlobalEventExecutor.INSTANCE.newSucceededFuture(Boolean.FALSE);
92      }
93  
94      /**
95       * If the pool implementation supports asynchronous close, then use it to avoid a blocking close call in case
96       * the ChannelPoolMap operations are called from an EventLoop.
97       *
98       * @param pool the ChannelPool to be closed
99       */
100     private static Future<Void> poolCloseAsyncIfSupported(ChannelPool pool) {
101         if (pool instanceof SimpleChannelPool) {
102             return ((SimpleChannelPool) pool).closeAsync();
103         } else {
104             try {
105                 pool.close();
106                 return GlobalEventExecutor.INSTANCE.newSucceededFuture(null);
107             } catch (Exception e) {
108                 return GlobalEventExecutor.INSTANCE.newFailedFuture(e);
109             }
110         }
111     }
112 
113     @Override
114     public final Iterator<Entry<K, P>> iterator() {
115         return new ReadOnlyIterator<Entry<K, P>>(map.entrySet().iterator());
116     }
117 
118     /**
119      * Returns the number of {@link ChannelPool}s currently in this {@link AbstractChannelPoolMap}.
120      */
121     public final int size() {
122         return map.size();
123     }
124 
125     /**
126      * Returns {@code true} if the {@link AbstractChannelPoolMap} is empty, otherwise {@code false}.
127      */
128     public final boolean isEmpty() {
129         return map.isEmpty();
130     }
131 
132     @Override
133     public final boolean contains(K key) {
134         return map.containsKey(checkNotNull(key, "key"));
135     }
136 
137     /**
138      * Called once a new {@link ChannelPool} needs to be created as non exists yet for the {@code key}.
139      */
140     protected abstract P newPool(K key);
141 
142     @Override
143     public final void close() {
144         for (K key: map.keySet()) {
145             // Wait for remove to finish to ensure that resources are released before returning from close
146             removeAsyncIfSupported(key).syncUninterruptibly();
147         }
148     }
149 }