1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.pool;
17
18 import io.netty.util.internal.PlatformDependent;
19 import io.netty.util.internal.ReadOnlyIterator;
20
21 import java.io.Closeable;
22 import java.util.Iterator;
23 import java.util.Map.Entry;
24 import java.util.concurrent.ConcurrentMap;
25
26 import static io.netty.util.internal.ObjectUtil.checkNotNull;
27
28
29
30
31
32 public abstract class AbstractChannelPoolMap<K, P extends ChannelPool>
33 implements ChannelPoolMap<K, P>, Iterable<Entry<K, P>>, Closeable {
34 private final ConcurrentMap<K, P> map = PlatformDependent.newConcurrentHashMap();
35
36 @Override
37 public final P get(K key) {
38 P pool = map.get(checkNotNull(key, "key"));
39 if (pool == null) {
40 pool = newPool(key);
41 P old = map.putIfAbsent(key, pool);
42 if (old != null) {
43
44 pool.close();
45 pool = old;
46 }
47 }
48 return pool;
49 }
50
51
52
53
54
55
56 public final boolean remove(K key) {
57 P pool = map.remove(checkNotNull(key, "key"));
58 if (pool != null) {
59 pool.close();
60 return true;
61 }
62 return false;
63 }
64
65 @Override
66 public final Iterator<Entry<K, P>> iterator() {
67 return new ReadOnlyIterator<Entry<K, P>>(map.entrySet().iterator());
68 }
69
70
71
72
73 public final int size() {
74 return map.size();
75 }
76
77
78
79
80 public final boolean isEmpty() {
81 return map.isEmpty();
82 }
83
84 @Override
85 public final boolean contains(K key) {
86 return map.containsKey(checkNotNull(key, "key"));
87 }
88
89
90
91
92 protected abstract P newPool(K key);
93
94 @Override
95 public final void close() {
96 for (K key: map.keySet()) {
97 remove(key);
98 }
99 }
100 }