View Javadoc

1   /**
2    * Copyright 2008 Atlassian Pty Ltd 
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); 
5    * you may not use this file except in compliance with the License.
6    * 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, 
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
13   * See the License for the specific language governing permissions and 
14   * limitations under the License.
15   */
16  
17  package com.atlassian.util.concurrent;
18  
19  import java.util.Collections;
20  import java.util.HashMap;
21  import java.util.LinkedHashMap;
22  import java.util.Map;
23  import java.util.TreeMap;
24  import java.util.WeakHashMap;
25  
26  import net.jcip.annotations.GuardedBy;
27  import net.jcip.annotations.ThreadSafe;
28  
29  /**
30   * A thread-safe variant of {@link Map} in which all mutative operations (the
31   * "destructive" operations described by {@link Map} put, remove and so on) are
32   * implemented by making a fresh copy of the underlying map.
33   * <p>
34   * This is ordinarily too costly, but may be <em>more</em> efficient than
35   * alternatives when traversal operations vastly out-number mutations, and is
36   * useful when you cannot or don't want to synchronize traversals, yet need to
37   * preclude interference among concurrent threads. The "snapshot" style
38   * iterators on the collections returned by {@link #entrySet()},
39   * {@link #keySet()} and {@link #values()} use a reference to the internal map
40   * at the point that the iterator was created. This map never changes during the
41   * lifetime of the iterator, so interference is impossible and the iterator is
42   * guaranteed not to throw <tt>ConcurrentModificationException</tt>. The
43   * iterators will not reflect additions, removals, or changes to the list since
44   * the iterator was created. Removing elements via these iterators is not
45   * supported. The mutable operations on these collections (remove, retain etc.)
46   * are supported but as with the {@link Map} interface, add and addAll are not
47   * and throw {@link UnsupportedOperationException}.
48   * <p>
49   * The actual copy is performed by an abstract {@link #copy(Map)} method. The
50   * method is responsible for the underlying Map implementation (for instance a
51   * {@link HashMap}, {@link TreeMap}, {@link LinkedHashMap} etc.) and therefore
52   * the semantics of what this map will cope with as far as null keys and values,
53   * iteration ordering etc. See the note below about suitable candidates for
54   * underlying Map implementations
55   * <p>
56   * There are supplied implementations for the common Collections {@link Map}
57   * implementations via the {@link CopyOnWriteMaps} static factory methods.
58   * <p>
59   * Collection views of the keys, values and entries are modifiable and will
60   * cause a copy.
61   * <p>
62   * <strong>Please note</strong> that the thread-safety guarantees are limited to
63   * the thread-safety of the non-mutative (non-destructive) operations of the
64   * underlying map implementation. For instance some implementations such as
65   * {@link WeakHashMap} and {@link LinkedHashMap} with access ordering are
66   * actually structurally modified by the {@link #get(Object)} method and are
67   * therefore not suitable candidates as delegates for this class.
68   * 
69   * @param <K> the key type
70   * @param <V> the value type
71   * @author Jed Wesley-Smith
72   */
73  @ThreadSafe
74  public abstract class CopyOnWriteMap<K, V> extends AbstractCopyOnWriteMap<K, V, Map<K, V>> {
75      private static final long serialVersionUID = 7935514534647505917L;
76  
77      /**
78       * Creates a new {@link CopyOnWriteMap} with an underlying {@link HashMap}.
79       */
80      public static <K, V> CopyOnWriteMap<K, V> newHashMap() {
81          return new CopyOnWriteMap<K, V>() {
82              private static final long serialVersionUID = 5221824943734164497L;
83  
84              @Override
85              public <N extends Map<? extends K, ? extends V>> Map<K, V> copy(final N map) {
86                  return new HashMap<K, V>(map);
87              }
88          };
89      }
90  
91      /**
92       * Creates a new {@link CopyOnWriteMap} with an underlying {@link HashMap}
93       * using the supplied map as the initial values.
94       */
95      public static <K, V> CopyOnWriteMap<K, V> newHashMap(final Map<? extends K, ? extends V> map) {
96          return new CopyOnWriteMap<K, V>(map) {
97              private static final long serialVersionUID = -7616159260882572421L;
98  
99              @Override
100             public <N extends Map<? extends K, ? extends V>> Map<K, V> copy(final N map) {
101                 return new HashMap<K, V>(map);
102             }
103         };
104     }
105 
106     /**
107      * Creates a new {@link CopyOnWriteMap} with an underlying
108      * {@link LinkedHashMap}. Iterators for this map will be return elements in
109      * insertion order.
110      */
111     public static <K, V> CopyOnWriteMap<K, V> newLinkedMap() {
112         return new CopyOnWriteMap<K, V>() {
113             private static final long serialVersionUID = -4597421704607601676L;
114 
115             @Override
116             public <N extends Map<? extends K, ? extends V>> Map<K, V> copy(final N map) {
117                 return new LinkedHashMap<K, V>(map);
118             }
119         };
120     }
121 
122     /**
123      * Creates a new {@link CopyOnWriteMap} with an underlying
124      * {@link LinkedHashMap} using the supplied map as the initial values.
125      * Iterators for this map will be return elements in insertion order.
126      */
127     public static <K, V> CopyOnWriteMap<K, V> newLinkedMap(final Map<? extends K, ? extends V> map) {
128         return new CopyOnWriteMap<K, V>(map) {
129             private static final long serialVersionUID = -8659999465009072124L;
130 
131             @Override
132             public <N extends Map<? extends K, ? extends V>> Map<K, V> copy(final N map) {
133                 return new LinkedHashMap<K, V>(map);
134             }
135         };
136     }
137 
138     //
139     // constructors
140     //
141 
142     /**
143      * Create a new {@link CopyOnWriteMap} with the supplied {@link Map} to
144      * initialize the values.
145      * 
146      * @param map the initial map to initialize with
147      */
148     public CopyOnWriteMap(final Map<? extends K, ? extends V> map) {
149         super(map);
150     }
151 
152     /**
153      * Create a new empty {@link CopyOnWriteMap}.
154      */
155     public CopyOnWriteMap() {
156         super(Collections.<K, V> emptyMap());
157     }
158 
159     @Override
160     @GuardedBy("internal-lock")
161     protected abstract <N extends Map<? extends K, ? extends V>> Map<K, V> copy(N map);
162 }