ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ConcurrentHashMapTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ConcurrentHashMapTest.java (file contents):
Revision 1.3 by dl, Sun Sep 14 20:42:40 2003 UTC vs.
Revision 1.64 by jsr166, Tue Jan 26 18:03:27 2021 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5 > * http://creativecommons.org/publicdomain/zero/1.0/
6 > * Other contributors include Andrew Wright, Jeffrey Hayes,
7 > * Pat Fisher, Mike Judd.
8   */
9  
10 < import junit.framework.*;
11 < import java.util.*;
12 < import java.util.concurrent.*;
10 > import java.util.ArrayList;
11 > import java.util.Arrays;
12 > import java.util.Collection;
13 > import java.util.Collections;
14   import java.util.Enumeration;
15 < import java.io.*;
15 > import java.util.Iterator;
16 > import java.util.Map;
17 > import java.util.Random;
18 > import java.util.Set;
19 > import java.util.concurrent.ConcurrentHashMap;
20  
21 < public class ConcurrentHashMapTest extends JSR166TestCase{
21 > import junit.framework.Test;
22 >
23 > public class ConcurrentHashMapTest extends JSR166TestCase {
24      public static void main(String[] args) {
25 <        junit.textui.TestRunner.run (suite());  
25 >        main(suite(), args);
26      }
27      public static Test suite() {
28 <        return new TestSuite(ConcurrentHashMapTest.class);
28 >        class Implementation implements MapImplementation {
29 >            public Class<?> klazz() { return ConcurrentHashMap.class; }
30 >            public Map emptyMap() { return new ConcurrentHashMap(); }
31 >            public boolean isConcurrent() { return true; }
32 >            public boolean permitsNullKeys() { return false; }
33 >            public boolean permitsNullValues() { return false; }
34 >            public boolean supportsSetValue() { return true; }
35 >        }
36 >        return newTestSuite(
37 >            ConcurrentHashMapTest.class,
38 >            MapTest.testSuite(new Implementation()));
39      }
40  
41 <    private static ConcurrentHashMap map5() {  
42 <        ConcurrentHashMap map = new ConcurrentHashMap(5);
41 >    /**
42 >     * Returns a new map from Items 1-5 to Strings "A"-"E".
43 >     */
44 >    private static ConcurrentHashMap<Item, String> map5() {
45 >        ConcurrentHashMap<Item, String> map = new ConcurrentHashMap<>(5);
46          assertTrue(map.isEmpty());
47 <        map.put(one, "A");
48 <        map.put(two, "B");
49 <        map.put(three, "C");
50 <        map.put(four, "D");
51 <        map.put(five, "E");
47 >        map.put(one, "A");
48 >        map.put(two, "B");
49 >        map.put(three, "C");
50 >        map.put(four, "D");
51 >        map.put(five, "E");
52          assertFalse(map.isEmpty());
53 <        assertEquals(5, map.size());
54 <        return map;
53 >        mustEqual(5, map.size());
54 >        return map;
55 >    }
56 >
57 >    // classes for testing Comparable fallbacks
58 >    static class BI implements Comparable<BI> {
59 >        private final int value;
60 >        BI(int value) { this.value = value; }
61 >        public int compareTo(BI other) {
62 >            return Integer.compare(value, other.value);
63 >        }
64 >        public boolean equals(Object x) {
65 >            return (x instanceof BI) && ((BI)x).value == value;
66 >        }
67 >        public int hashCode() { return 42; }
68 >    }
69 >    static class CI extends BI { CI(int value) { super(value); } }
70 >    static class DI extends BI { DI(int value) { super(value); } }
71 >
72 >    static class BS implements Comparable<BS> {
73 >        private final String value;
74 >        BS(String value) { this.value = value; }
75 >        public int compareTo(BS other) {
76 >            return value.compareTo(other.value);
77 >        }
78 >        public boolean equals(Object x) {
79 >            return (x instanceof BS) && value.equals(((BS)x).value);
80 >        }
81 >        public int hashCode() { return 42; }
82 >    }
83 >
84 >    static class LexicographicList<E extends Comparable<E>> extends ArrayList<E>
85 >        implements Comparable<LexicographicList<E>> {
86 >        LexicographicList(Collection<E> c) { super(c); }
87 >        LexicographicList(E e) { super(Collections.singleton(e)); }
88 >        public int compareTo(LexicographicList<E> other) {
89 >            int common = Math.min(size(), other.size());
90 >            int r = 0;
91 >            for (int i = 0; i < common; i++) {
92 >                if ((r = get(i).compareTo(other.get(i))) != 0)
93 >                    break;
94 >            }
95 >            if (r == 0)
96 >                r = Integer.compare(size(), other.size());
97 >            return r;
98 >        }
99 >        private static final long serialVersionUID = 0;
100 >    }
101 >
102 >    static class CollidingObject {
103 >        final String value;
104 >        CollidingObject(final String value) { this.value = value; }
105 >        public int hashCode() { return this.value.hashCode() & 1; }
106 >        public boolean equals(final Object obj) {
107 >            return (obj instanceof CollidingObject) && ((CollidingObject)obj).value.equals(value);
108 >        }
109 >    }
110 >
111 >    static class ComparableCollidingObject extends CollidingObject implements Comparable<ComparableCollidingObject> {
112 >        ComparableCollidingObject(final String value) { super(value); }
113 >        public int compareTo(final ComparableCollidingObject o) {
114 >            return value.compareTo(o.value);
115 >        }
116      }
117  
118      /**
119 <     *   clear  removes all key-element pairs from the map
119 >     * Inserted elements that are subclasses of the same Comparable
120 >     * class are found.
121       */
122 <    public void testClear(){
123 <        ConcurrentHashMap map = map5();
124 <        map.clear();
125 <        assertEquals(map.size(), 0);
122 >    public void testComparableFamily() {
123 >        int size = 500;         // makes measured test run time -> 60ms
124 >        ConcurrentHashMap<BI, Boolean> m = new ConcurrentHashMap<>();
125 >        for (int i = 0; i < size; i++) {
126 >            assertNull(m.put(new CI(i), true));
127 >        }
128 >        for (int i = 0; i < size; i++) {
129 >            assertTrue(m.containsKey(new CI(i)));
130 >            assertTrue(m.containsKey(new DI(i)));
131 >        }
132      }
133  
134      /**
135 <     *   contains gives the appropriate value
135 >     * Elements of classes with erased generic type parameters based
136 >     * on Comparable can be inserted and found.
137       */
138 <    public void testContains(){
139 <        ConcurrentHashMap map = map5();
140 <        assertTrue(map.contains("A"));
141 <        assertFalse(map.contains("Z"));
138 >    public void testGenericComparable() {
139 >        int size = 120;         // makes measured test run time -> 60ms
140 >        ConcurrentHashMap<Object, Boolean> m = new ConcurrentHashMap<>();
141 >        for (int i = 0; i < size; i++) {
142 >            BI bi = new BI(i);
143 >            BS bs = new BS(String.valueOf(i));
144 >            LexicographicList<BI> bis = new LexicographicList<>(bi);
145 >            LexicographicList<BS> bss = new LexicographicList<>(bs);
146 >            assertNull(m.putIfAbsent(bis, true));
147 >            assertTrue(m.containsKey(bis));
148 >            if (m.putIfAbsent(bss, true) == null)
149 >                assertTrue(m.containsKey(bss));
150 >            assertTrue(m.containsKey(bis));
151 >        }
152 >        for (int i = 0; i < size; i++) {
153 >            assertTrue(m.containsKey(Collections.singletonList(new BI(i))));
154 >        }
155      }
156 <    
156 >
157 >    /**
158 >     * Elements of non-comparable classes equal to those of classes
159 >     * with erased generic type parameters based on Comparable can be
160 >     * inserted and found.
161 >     */
162 >    public void testGenericComparable2() {
163 >        int size = 500;         // makes measured test run time -> 60ms
164 >        ConcurrentHashMap<Object, Boolean> m = new ConcurrentHashMap<>();
165 >        for (int i = 0; i < size; i++) {
166 >            m.put(Collections.singletonList(new BI(i)), true);
167 >        }
168 >
169 >        for (int i = 0; i < size; i++) {
170 >            LexicographicList<BI> bis = new LexicographicList<>(new BI(i));
171 >            assertTrue(m.containsKey(bis));
172 >        }
173 >    }
174 >
175 >    /**
176 >     * Mixtures of instances of comparable and non-comparable classes
177 >     * can be inserted and found.
178 >     */
179 >    public void testMixedComparable() {
180 >        int size = 1200;        // makes measured test run time -> 35ms
181 >        ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();
182 >        Random rng = new Random();
183 >        for (int i = 0; i < size; i++) {
184 >            Object x;
185 >            switch (rng.nextInt(4)) {
186 >            case 0:
187 >                x = new Object();
188 >                break;
189 >            case 1:
190 >                x = new CollidingObject(Integer.toString(i));
191 >                break;
192 >            default:
193 >                x = new ComparableCollidingObject(Integer.toString(i));
194 >            }
195 >            assertNull(map.put(x, x));
196 >        }
197 >        int count = 0;
198 >        for (Object k : map.keySet()) {
199 >            mustEqual(map.get(k), k);
200 >            ++count;
201 >        }
202 >        mustEqual(count, size);
203 >        mustEqual(map.size(), size);
204 >        for (Object k : map.keySet()) {
205 >            mustEqual(map.put(k, k), k);
206 >        }
207 >    }
208 >
209      /**
210 <     *   containsKey gives the appropriate value
210 >     * clear removes all pairs
211       */
212 <    public void testContainsKey(){
213 <        ConcurrentHashMap map = map5();
214 <        assertTrue(map.containsKey(one));
215 <        assertFalse(map.containsKey(new Integer(100)));
212 >    public void testClear() {
213 >        ConcurrentHashMap<Item,String> map = map5();
214 >        map.clear();
215 >        mustEqual(0, map.size());
216      }
217  
218      /**
219 <     *  Identical to normal contains
219 >     * Maps with same contents are equal
220       */
221 <    public void testContainsValue(){
222 <        ConcurrentHashMap map = map5();
223 <        assertTrue(map.contains("A"));
221 >    public void testEquals() {
222 >        ConcurrentHashMap<Item,String> map1 = map5();
223 >        ConcurrentHashMap<Item,String> map2 = map5();
224 >        mustEqual(map1, map2);
225 >        mustEqual(map2, map1);
226 >        map1.clear();
227 >        assertFalse(map1.equals(map2));
228 >        assertFalse(map2.equals(map1));
229 >    }
230 >
231 >    /**
232 >     * hashCode() equals sum of each key.hashCode ^ value.hashCode
233 >     */
234 >    public void testHashCode() {
235 >        ConcurrentHashMap<Item,String> map = map5();
236 >        int sum = 0;
237 >        for (Map.Entry<Item,String> e : map.entrySet())
238 >            sum += e.getKey().hashCode() ^ e.getValue().hashCode();
239 >        mustEqual(sum, map.hashCode());
240 >    }
241 >
242 >    /**
243 >     * contains returns true for contained value
244 >     */
245 >    public void testContains() {
246 >        ConcurrentHashMap<Item,String> map = map5();
247 >        assertTrue(map.contains("A"));
248          assertFalse(map.contains("Z"));
249      }
250  
251      /**
252 <     *  tes to verify enumeration returns an enumeration containing the correct elements
252 >     * containsKey returns true for contained key
253 >     */
254 >    public void testContainsKey() {
255 >        ConcurrentHashMap<Item,String> map = map5();
256 >        assertTrue(map.containsKey(one));
257 >        assertFalse(map.containsKey(zero));
258 >    }
259 >
260 >    /**
261 >     * containsValue returns true for held values
262       */
263 <    public void testEnumeration(){
264 <        ConcurrentHashMap map = map5();
265 <        Enumeration e = map.elements();
266 <        int count = 0;
78 <        while(e.hasMoreElements()){
79 <            count++;
80 <            e.nextElement();
81 <        }
82 <        assertEquals(5, count);
263 >    public void testContainsValue() {
264 >        ConcurrentHashMap<Item,String> map = map5();
265 >        assertTrue(map.containsValue("A"));
266 >        assertFalse(map.containsValue("Z"));
267      }
268  
269      /**
270 <     *   get returns the correct element at the given index
270 >     * enumeration returns an enumeration containing the correct
271 >     * elements
272       */
273 <    public void testGet(){
274 <        ConcurrentHashMap map = map5();
275 <        assertEquals("A", (String)map.get(one));
273 >    public void testEnumeration() {
274 >        ConcurrentHashMap<Item,String> map = map5();
275 >        Enumeration<String> e = map.elements();
276 >        int count = 0;
277 >        while (e.hasMoreElements()) {
278 >            count++;
279 >            e.nextElement();
280 >        }
281 >        mustEqual(5, count);
282      }
283  
284      /**
285 <     *   get on a nonexistant key returns null
285 >     * get returns the correct element at the given key,
286 >     * or null if not present
287       */
288 <    public void testGet2(){
289 <        ConcurrentHashMap empty = new ConcurrentHashMap();
288 >    public void testGet() {
289 >        ConcurrentHashMap<Item,String> map = map5();
290 >        mustEqual("A", map.get(one));
291 >        ConcurrentHashMap<Item,String> empty = new ConcurrentHashMap<Item,String>();
292 >        assertNull(map.get("anything"));
293          assertNull(empty.get("anything"));
294      }
295  
296      /**
297 <     *  Simple test to verify isEmpty returns the correct value
297 >     * isEmpty is true of empty map and false for non-empty
298       */
299 <    public void testIsEmpty(){
300 <        ConcurrentHashMap empty = new ConcurrentHashMap();
301 <        ConcurrentHashMap map = map5();
302 <        assertTrue(empty.isEmpty());
299 >    public void testIsEmpty() {
300 >        ConcurrentHashMap<Item,String> empty = new ConcurrentHashMap<Item,String>();
301 >        ConcurrentHashMap<Item,String> map = map5();
302 >        assertTrue(empty.isEmpty());
303          assertFalse(map.isEmpty());
304      }
305  
306      /**
307 <     *   keys returns an enumeration containing all the keys from the map
307 >     * keys returns an enumeration containing all the keys from the map
308 >     */
309 >    public void testKeys() {
310 >        ConcurrentHashMap<Item,String> map = map5();
311 >        Enumeration<Item> e = map.keys();
312 >        int count = 0;
313 >        while (e.hasMoreElements()) {
314 >            count++;
315 >            e.nextElement();
316 >        }
317 >        mustEqual(5, count);
318 >    }
319 >
320 >    /**
321 >     * keySet returns a Set containing all the keys
322 >     */
323 >    public void testKeySet() {
324 >        ConcurrentHashMap<Item,String> map = map5();
325 >        Set<Item> s = map.keySet();
326 >        mustEqual(5, s.size());
327 >        mustContain(s, one);
328 >        mustContain(s, two);
329 >        mustContain(s, three);
330 >        mustContain(s, four);
331 >        mustContain(s, five);
332 >    }
333 >
334 >    /**
335 >     * Test keySet().removeAll on empty map
336 >     */
337 >    public void testKeySet_empty_removeAll() {
338 >        ConcurrentHashMap<Item, String> map = new ConcurrentHashMap<>();
339 >        Set<Item> set = map.keySet();
340 >        set.removeAll(Collections.emptyList());
341 >        assertTrue(map.isEmpty());
342 >        assertTrue(set.isEmpty());
343 >        // following is test for JDK-8163353
344 >        set.removeAll(Collections.emptySet());
345 >        assertTrue(map.isEmpty());
346 >        assertTrue(set.isEmpty());
347 >    }
348 >
349 >    /**
350 >     * keySet.toArray returns contains all keys
351 >     */
352 >    public void testKeySetToArray() {
353 >        ConcurrentHashMap<Item,String> map = map5();
354 >        Set<Item> s = map.keySet();
355 >        Object[] ar = s.toArray();
356 >        assertTrue(s.containsAll(Arrays.asList(ar)));
357 >        mustEqual(5, ar.length);
358 >        ar[0] = minusTen;
359 >        assertFalse(s.containsAll(Arrays.asList(ar)));
360 >    }
361 >
362 >    /**
363 >     * Values.toArray contains all values
364 >     */
365 >    public void testValuesToArray() {
366 >        ConcurrentHashMap<Item,String> map = map5();
367 >        Collection<String> v = map.values();
368 >        String[] ar = v.toArray(new String[0]);
369 >        ArrayList<String> s = new ArrayList<String>(Arrays.asList(ar));
370 >        mustEqual(5, ar.length);
371 >        assertTrue(s.contains("A"));
372 >        assertTrue(s.contains("B"));
373 >        assertTrue(s.contains("C"));
374 >        assertTrue(s.contains("D"));
375 >        assertTrue(s.contains("E"));
376 >    }
377 >
378 >    /**
379 >     * entrySet.toArray contains all entries
380 >     */
381 >    public void testEntrySetToArray() {
382 >        ConcurrentHashMap<Item,String> map = map5();
383 >        Set<Map.Entry<Item,String>> s = map.entrySet();
384 >        Object[] ar = s.toArray();
385 >        mustEqual(5, ar.length);
386 >        for (int i = 0; i < 5; ++i) {
387 >            assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
388 >            assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
389 >        }
390 >    }
391 >
392 >    /**
393 >     * values collection contains all values
394       */
395 <    public void testKeys(){
396 <        ConcurrentHashMap map = map5();
397 <        Enumeration e = map.keys();
398 <        int count = 0;
399 <        while(e.hasMoreElements()){
400 <            count++;
401 <            e.nextElement();
402 <        }
403 <        assertEquals(5, count);
395 >    public void testValues() {
396 >        ConcurrentHashMap<Item,String> map = map5();
397 >        Collection<String> s = map.values();
398 >        mustEqual(5, s.size());
399 >        assertTrue(s.contains("A"));
400 >        assertTrue(s.contains("B"));
401 >        assertTrue(s.contains("C"));
402 >        assertTrue(s.contains("D"));
403 >        assertTrue(s.contains("E"));
404      }
405  
406      /**
407 <     *   keySet returns a Set containing all the keys
408 <     */
409 <    public void testKeySet(){
410 <        ConcurrentHashMap map = map5();
411 <        Set s = map.keySet();
412 <        assertEquals(5, s.size());
413 <        assertTrue(s.contains(one));
133 <        assertTrue(s.contains(two));
134 <        assertTrue(s.contains(three));
135 <        assertTrue(s.contains(four));
136 <        assertTrue(s.contains(five));
137 <    }
138 <
139 <    public void testValues(){
140 <        ConcurrentHashMap map = map5();
141 <        Collection s = map.values();
142 <        assertEquals(5, s.size());
143 <        assertTrue(s.contains("A"));
144 <        assertTrue(s.contains("B"));
145 <        assertTrue(s.contains("C"));
146 <        assertTrue(s.contains("D"));
147 <        assertTrue(s.contains("E"));
148 <    }
149 <
150 <    public void testEntrySet(){
151 <        ConcurrentHashMap map = map5();
152 <        Set s = map.entrySet();
153 <        assertEquals(5, s.size());
154 <        Iterator it = s.iterator();
407 >     * entrySet contains all pairs
408 >     */
409 >    public void testEntrySet() {
410 >        ConcurrentHashMap<Item, String> map = map5();
411 >        Set<Map.Entry<Item,String>> s = map.entrySet();
412 >        mustEqual(5, s.size());
413 >        Iterator<Map.Entry<Item,String>> it = s.iterator();
414          while (it.hasNext()) {
415 <            Map.Entry e = (Map.Entry) it.next();
416 <            assertTrue(
415 >            Map.Entry<Item,String> e = it.next();
416 >            assertTrue(
417                         (e.getKey().equals(one) && e.getValue().equals("A")) ||
418                         (e.getKey().equals(two) && e.getValue().equals("B")) ||
419                         (e.getKey().equals(three) && e.getValue().equals("C")) ||
# Line 164 | Line 423 | public class ConcurrentHashMapTest exten
423      }
424  
425      /**
426 <     *   putAll  adds all key-value pairs from the given map
426 >     * putAll adds all key-value pairs from the given map
427 >     */
428 >    public void testPutAll() {
429 >        ConcurrentHashMap<Item,String> p = new ConcurrentHashMap<Item,String>();
430 >        ConcurrentHashMap<Item,String> map = map5();
431 >        p.putAll(map);
432 >        mustEqual(5, p.size());
433 >        assertTrue(p.containsKey(one));
434 >        assertTrue(p.containsKey(two));
435 >        assertTrue(p.containsKey(three));
436 >        assertTrue(p.containsKey(four));
437 >        assertTrue(p.containsKey(five));
438 >    }
439 >
440 >    /**
441 >     * putIfAbsent works when the given key is not present
442 >     */
443 >    public void testPutIfAbsent() {
444 >        ConcurrentHashMap<Item,String> map = map5();
445 >        map.putIfAbsent(six, "Z");
446 >        assertTrue(map.containsKey(six));
447 >    }
448 >
449 >    /**
450 >     * putIfAbsent does not add the pair if the key is already present
451 >     */
452 >    public void testPutIfAbsent2() {
453 >        ConcurrentHashMap<Item,String> map = map5();
454 >        mustEqual("A", map.putIfAbsent(one, "Z"));
455 >    }
456 >
457 >    /**
458 >     * replace fails when the given key is not present
459       */
460 <    public void testPutAll(){
461 <        ConcurrentHashMap empty = new ConcurrentHashMap();
462 <        ConcurrentHashMap map = map5();
463 <        empty.putAll(map);
173 <        assertEquals(5, empty.size());
174 <        assertTrue(empty.containsKey(one));
175 <        assertTrue(empty.containsKey(two));
176 <        assertTrue(empty.containsKey(three));
177 <        assertTrue(empty.containsKey(four));
178 <        assertTrue(empty.containsKey(five));
460 >    public void testReplace() {
461 >        ConcurrentHashMap<Item,String> map = map5();
462 >        assertNull(map.replace(six, "Z"));
463 >        assertFalse(map.containsKey(six));
464      }
465  
466      /**
467 <     *   putIfAbsent works when the given key is not present
467 >     * replace succeeds if the key is already present
468       */
469 <    public void testPutIfAbsent(){
470 <        ConcurrentHashMap map = map5();
471 <        map.putIfAbsent(new Integer(6), "Z");
472 <        assertTrue(map.containsKey(new Integer(6)));
469 >    public void testReplace2() {
470 >        ConcurrentHashMap<Item,String> map = map5();
471 >        assertNotNull(map.replace(one, "Z"));
472 >        mustEqual("Z", map.get(one));
473      }
474  
475      /**
476 <     *   putIfAbsent does not add the pair if the key is already present
476 >     * replace value fails when the given key not mapped to expected value
477       */
478 <    public void testPutIfAbsent2(){
479 <        ConcurrentHashMap map = map5();
480 <        assertEquals("A", map.putIfAbsent(one, "Z"));
478 >    public void testReplaceValue() {
479 >        ConcurrentHashMap<Item,String> map = map5();
480 >        mustEqual("A", map.get(one));
481 >        assertFalse(map.replace(one, "Z", "Z"));
482 >        mustEqual("A", map.get(one));
483      }
484  
485      /**
486 <     *   remove removes the correct key-value pair from the map
486 >     * replace value succeeds when the given key mapped to expected value
487       */
488 <    public void testRemove(){
489 <        ConcurrentHashMap map = map5();
490 <        map.remove(five);
491 <        assertEquals(4, map.size());
492 <        assertFalse(map.containsKey(five));
488 >    public void testReplaceValue2() {
489 >        ConcurrentHashMap<Item,String> map = map5();
490 >        mustEqual("A", map.get(one));
491 >        assertTrue(map.replace(one, "A", "Z"));
492 >        mustEqual("Z", map.get(one));
493      }
494  
495 <    public void testRemove2(){
496 <        ConcurrentHashMap map = map5();
497 <        map.remove(five, "E");
498 <        assertEquals(4, map.size());
499 <        assertFalse(map.containsKey(five));
500 <        map.remove(four, "A");
501 <        assertEquals(4, map.size());
502 <        assertTrue(map.containsKey(four));
495 >    /**
496 >     * remove removes the correct key-value pair from the map
497 >     */
498 >    public void testRemove() {
499 >        ConcurrentHashMap<Item,String> map = map5();
500 >        map.remove(five);
501 >        mustEqual(4, map.size());
502 >        assertFalse(map.containsKey(five));
503 >    }
504  
505 +    /**
506 +     * remove(key,value) removes only if pair present
507 +     */
508 +    public void testRemove2() {
509 +        ConcurrentHashMap<Item,String> map = map5();
510 +        map.remove(five, "E");
511 +        mustEqual(4, map.size());
512 +        assertFalse(map.containsKey(five));
513 +        map.remove(four, "A");
514 +        mustEqual(4, map.size());
515 +        assertTrue(map.containsKey(four));
516      }
517  
518      /**
519 <     *   size returns the correct values
519 >     * size returns the correct values
520       */
521 <    public void testSize(){
522 <        ConcurrentHashMap map = map5();
523 <        ConcurrentHashMap empty = new ConcurrentHashMap();
524 <        assertEquals(0, empty.size());
525 <        assertEquals(5, map.size());
521 >    public void testSize() {
522 >        ConcurrentHashMap<Item,String> map = map5();
523 >        ConcurrentHashMap<Item,String> empty = new ConcurrentHashMap<Item,String>();
524 >        mustEqual(0, empty.size());
525 >        mustEqual(5, map.size());
526      }
527  
528 <    public void testToString(){
529 <        ConcurrentHashMap map = map5();
528 >    /**
529 >     * toString contains toString of elements
530 >     */
531 >    public void testToString() {
532 >        ConcurrentHashMap<Item,String> map = map5();
533          String s = map.toString();
534          for (int i = 1; i <= 5; ++i) {
535 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
535 >            assertTrue(s.contains(String.valueOf(i)));
536          }
537 <    }        
537 >    }
538  
539      // Exception tests
540 <    
541 <    public void testConstructor1(){
542 <        try{
543 <            new ConcurrentHashMap(-1,0,1);
544 <            fail("ConcurrentHashMap(int, float, int) should throw Illegal Argument Exception");
545 <        }catch(IllegalArgumentException e){}
546 <    }
547 <
548 <    public void testConstructor2(){
549 <        try{
550 <            new ConcurrentHashMap(1,0,-1);
551 <            fail("ConcurrentHashMap(int, float, int) should throw Illegal Argument Exception");
552 <        }catch(IllegalArgumentException e){}
553 <    }
554 <
555 <    public void testConstructor3(){
556 <        try{
557 <            new ConcurrentHashMap(-1);
558 <            fail("ConcurrentHashMap(int) should throw Illegal Argument Exception");
559 <        }catch(IllegalArgumentException e){}
560 <    }
561 <
562 <    public void testGet_NullPointerException(){
563 <        try{
564 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
540 >
541 >    /**
542 >     * Cannot create with only negative capacity
543 >     */
544 >    public void testConstructor1() {
545 >        try {
546 >            new ConcurrentHashMap<Item,String>(-1);
547 >            shouldThrow();
548 >        } catch (IllegalArgumentException success) {}
549 >    }
550 >
551 >    /**
552 >     * Constructor (initialCapacity, loadFactor) throws
553 >     * IllegalArgumentException if either argument is negative
554 >     */
555 >    public void testConstructor2() {
556 >        try {
557 >            new ConcurrentHashMap<Item,String>(-1, .75f);
558 >            shouldThrow();
559 >        } catch (IllegalArgumentException success) {}
560 >
561 >        try {
562 >            new ConcurrentHashMap<Item,String>(16, -1);
563 >            shouldThrow();
564 >        } catch (IllegalArgumentException success) {}
565 >    }
566 >
567 >    /**
568 >     * Constructor (initialCapacity, loadFactor, concurrencyLevel)
569 >     * throws IllegalArgumentException if any argument is negative
570 >     */
571 >    public void testConstructor3() {
572 >        try {
573 >            new ConcurrentHashMap<Item,String>(-1, .75f, 1);
574 >            shouldThrow();
575 >        } catch (IllegalArgumentException success) {}
576 >
577 >        try {
578 >            new ConcurrentHashMap<Item,String>(16, -1, 1);
579 >            shouldThrow();
580 >        } catch (IllegalArgumentException success) {}
581 >
582 >        try {
583 >            new ConcurrentHashMap<Item,String>(16, .75f, -1);
584 >            shouldThrow();
585 >        } catch (IllegalArgumentException success) {}
586 >    }
587 >
588 >    /**
589 >     * ConcurrentHashMap(map) throws NullPointerException if the given
590 >     * map is null
591 >     */
592 >    public void testConstructor4() {
593 >        try {
594 >            new ConcurrentHashMap<Item,String>(null);
595 >            shouldThrow();
596 >        } catch (NullPointerException success) {}
597 >    }
598 >
599 >    /**
600 >     * ConcurrentHashMap(map) creates a new map with the same mappings
601 >     * as the given map
602 >     */
603 >    public void testConstructor5() {
604 >        ConcurrentHashMap<Item,String> map1 = map5();
605 >        ConcurrentHashMap<Item,String> map2 = new ConcurrentHashMap<Item,String>(map1);
606 >        assertTrue(map2.equals(map1));
607 >        map2.put(one, "F");
608 >        assertFalse(map2.equals(map1));
609 >    }
610 >
611 >    /**
612 >     * get(null) throws NPE
613 >     */
614 >    public void testGet_NullPointerException() {
615 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
616 >        try {
617              c.get(null);
618 <            fail("ConcurrentHashMap - Object get(Object) should throw Null Pointer exception");
619 <        }catch(NullPointerException e){}
618 >            shouldThrow();
619 >        } catch (NullPointerException success) {}
620      }
621  
622 <    public void testContainsKey_NullPointerException(){
623 <        try{
624 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
622 >    /**
623 >     * containsKey(null) throws NPE
624 >     */
625 >    public void testContainsKey_NullPointerException() {
626 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
627 >        try {
628              c.containsKey(null);
629 <            fail("ConcurrenthashMap - boolean containsKey(Object) should throw Null Pointer exception");
630 <        }catch(NullPointerException e){}
629 >            shouldThrow();
630 >        } catch (NullPointerException success) {}
631      }
632  
633 <    public void testContainsValue_NullPointerException(){
634 <        try{
635 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
633 >    /**
634 >     * containsValue(null) throws NPE
635 >     */
636 >    public void testContainsValue_NullPointerException() {
637 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
638 >        try {
639              c.containsValue(null);
640 <            fail("ConcurrentHashMap - boolean containsValue(Object) should throw Null Pointer exception");
641 <        }catch(NullPointerException e){}
640 >            shouldThrow();
641 >        } catch (NullPointerException success) {}
642      }
643  
644 <    public void testContains_NullPointerException(){
645 <        try{
646 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
644 >    /**
645 >     * contains(null) throws NPE
646 >     */
647 >    public void testContains_NullPointerException() {
648 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
649 >        try {
650              c.contains(null);
651 <            fail("ConcurrentHashMap - boolean contains(Object) should throw Null Pointer exception");
652 <        }catch(NullPointerException e){}
651 >            shouldThrow();
652 >        } catch (NullPointerException success) {}
653      }
654  
655 <    public void testPut1_NullPointerException(){
656 <        try{
657 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
655 >    /**
656 >     * put(null,x) throws NPE
657 >     */
658 >    public void testPut1_NullPointerException() {
659 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
660 >        try {
661              c.put(null, "whatever");
662 <            fail("ConcurrentHashMap - Object put(Object, Object) should throw Null Pointer exception");
663 <        }catch(NullPointerException e){}
662 >            shouldThrow();
663 >        } catch (NullPointerException success) {}
664      }
665  
666 <    public void testPut2_NullPointerException(){
667 <        try{
668 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
669 <            c.put("whatever", null);
670 <            fail("ConcurrentHashMap - Object put(Object, Object) should throw Null Pointer exception");
671 <        }catch(NullPointerException e){}
666 >    /**
667 >     * put(x, null) throws NPE
668 >     */
669 >    public void testPut2_NullPointerException() {
670 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
671 >        try {
672 >            c.put(zero, null);
673 >            shouldThrow();
674 >        } catch (NullPointerException success) {}
675      }
676  
677 <    public void testPutIfAbsent1_NullPointerException(){
678 <        try{
679 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
677 >    /**
678 >     * putIfAbsent(null, x) throws NPE
679 >     */
680 >    public void testPutIfAbsent1_NullPointerException() {
681 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
682 >        try {
683              c.putIfAbsent(null, "whatever");
684 <            fail("ConcurrentHashMap - Object putIfAbsent(Object, Object) should throw Null Pointer exception");
685 <        }catch(NullPointerException e){}
684 >            shouldThrow();
685 >        } catch (NullPointerException success) {}
686      }
687  
688 <    public void testPutIfAbsent2_NullPointerException(){
689 <        try{
690 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
691 <            c.putIfAbsent("whatever", null);
692 <            fail("COncurrentHashMap - Object putIfAbsent(Object, Object) should throw Null Pointer exception");
693 <        }catch(NullPointerException e){}
688 >    /**
689 >     * replace(null, x) throws NPE
690 >     */
691 >    public void testReplace_NullPointerException() {
692 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
693 >        try {
694 >            c.replace(null, "whatever");
695 >            shouldThrow();
696 >        } catch (NullPointerException success) {}
697      }
698  
699 +    /**
700 +     * replace(null, x, y) throws NPE
701 +     */
702 +    public void testReplaceValue_NullPointerException() {
703 +        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
704 +        try {
705 +            c.replace(null, "A", "B");
706 +            shouldThrow();
707 +        } catch (NullPointerException success) {}
708 +    }
709 +
710 +    /**
711 +     * putIfAbsent(x, null) throws NPE
712 +     */
713 +    public void testPutIfAbsent2_NullPointerException() {
714 +        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
715 +        try {
716 +            c.putIfAbsent(zero, null);
717 +            shouldThrow();
718 +        } catch (NullPointerException success) {}
719 +    }
720 +
721 +    /**
722 +     * replace(x, null) throws NPE
723 +     */
724 +    public void testReplace2_NullPointerException() {
725 +        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
726 +        try {
727 +            c.replace(one, null);
728 +            shouldThrow();
729 +        } catch (NullPointerException success) {}
730 +    }
731  
732 <    public void testRemove1_NullPointerException(){
733 <        try{
734 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
735 <            c.put("sadsdf", "asdads");
732 >    /**
733 >     * replace(x, null, y) throws NPE
734 >     */
735 >    public void testReplaceValue2_NullPointerException() {
736 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
737 >        try {
738 >            c.replace(one, null, "A");
739 >            shouldThrow();
740 >        } catch (NullPointerException success) {}
741 >    }
742 >
743 >    /**
744 >     * replace(x, y, null) throws NPE
745 >     */
746 >    public void testReplaceValue3_NullPointerException() {
747 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
748 >        try {
749 >            c.replace(zero, "A", null);
750 >            shouldThrow();
751 >        } catch (NullPointerException success) {}
752 >    }
753 >
754 >    /**
755 >     * remove(null) throws NPE
756 >     */
757 >    public void testRemove1_NullPointerException() {
758 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
759 >        c.put(one, "asdads");
760 >        try {
761              c.remove(null);
762 <            fail("ConcurrentHashMap - Object remove(Object) should throw Null pointer exceptione");
763 <        }catch(NullPointerException e){}
762 >            shouldThrow();
763 >        } catch (NullPointerException success) {}
764      }
765  
766 <    public void testRemove2_NullPointerException(){
767 <        try{
768 <            ConcurrentHashMap c = new ConcurrentHashMap(5);
769 <            c.put("sadsdf", "asdads");
766 >    /**
767 >     * remove(null, x) throws NPE
768 >     */
769 >    public void testRemove2_NullPointerException() {
770 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
771 >        c.put(one, "asdads");
772 >        try {
773              c.remove(null, "whatever");
774 <            fail("ConcurrentHashMap - Object remove(Object, Object) should throw Null pointer exceptione");
775 <        }catch(NullPointerException e){}
774 >            shouldThrow();
775 >        } catch (NullPointerException success) {}
776      }
777  
778 <    public void testSerialization() {
779 <        ConcurrentHashMap q = map5();
778 >    /**
779 >     * remove(x, null) returns false
780 >     */
781 >    public void testRemove3() {
782 >        ConcurrentHashMap<Item,String> c = new ConcurrentHashMap<Item,String>(5);
783 >        c.put(one, "asdads");
784 >        assertFalse(c.remove(one, null));
785 >    }
786  
787 <        try {
788 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
789 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
790 <            out.writeObject(q);
791 <            out.close();
787 >    /**
788 >     * A deserialized/reserialized map equals original
789 >     */
790 >    public void testSerialization() throws Exception {
791 >        Map<Item,String> x = map5();
792 >        Map<Item,String> y = serialClone(x);
793  
794 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
795 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
796 <            ConcurrentHashMap r = (ConcurrentHashMap)in.readObject();
797 <            assertEquals(q.size(), r.size());
798 <            assertTrue(q.equals(r));
799 <            assertTrue(r.equals(q));
800 <        } catch(Exception e){
801 <            e.printStackTrace();
802 <            fail("unexpected exception");
794 >        assertNotSame(x, y);
795 >        mustEqual(x.size(), y.size());
796 >        mustEqual(x, y);
797 >        mustEqual(y, x);
798 >    }
799 >
800 >    /**
801 >     * SetValue of an EntrySet entry sets value in the map.
802 >     */
803 >    @SuppressWarnings("unchecked")
804 >    public void testSetValueWriteThrough() {
805 >        // Adapted from a bug report by Eric Zoerner
806 >        ConcurrentHashMap<Object,Object> map = new ConcurrentHashMap<Object,Object>(2, 5.0f, 1);
807 >        assertTrue(map.isEmpty());
808 >        for (int i = 0; i < 20; i++)
809 >            map.put(itemFor(i), itemFor(i));
810 >        assertFalse(map.isEmpty());
811 >        Item key = itemFor(16);
812 >        Map.Entry<Object,Object> entry1 = map.entrySet().iterator().next();
813 >        // Unless it happens to be first (in which case remainder of
814 >        // test is skipped), remove a possibly-colliding key from map
815 >        // which, under some implementations, may cause entry1 to be
816 >        // cloned in map
817 >        if (!entry1.getKey().equals(key)) {
818 >            map.remove(key);
819 >            entry1.setValue("XYZ");
820 >            assertTrue(map.containsValue("XYZ")); // fails if write-through broken
821 >        }
822 >    }
823 >
824 >    /**
825 >     * Tests performance of removeAll when the other collection is much smaller.
826 >     * ant -Djsr166.tckTestClass=ConcurrentHashMapTest -Djsr166.methodFilter=testRemoveAll_performance -Djsr166.expensiveTests=true tck
827 >     */
828 >    public void testRemoveAll_performance() {
829 >        final int mapSize = expensiveTests ? 1_000_000 : 100;
830 >        final int iterations = expensiveTests ? 500 : 2;
831 >        final ConcurrentHashMap<Item, Item> map = new ConcurrentHashMap<>();
832 >        for (int i = 0; i < mapSize; i++) {
833 >            Item I = itemFor(i);
834 >            map.put(I, I);
835          }
836 +        Set<Item> keySet = map.keySet();
837 +        Collection<Item> removeMe = Arrays.asList(new Item[] { minusOne, minusTwo });
838 +        for (int i = 0; i < iterations; i++)
839 +            assertFalse(keySet.removeAll(removeMe));
840 +        mustEqual(mapSize, map.size());
841 +    }
842 +
843 +    public void testReentrantComputeIfAbsent() {
844 +        ConcurrentHashMap<Item, Item> map = new ConcurrentHashMap<>(16);
845 +        try {
846 +            for (int i = 0; i < 100; i++) { // force a resize
847 +                map.computeIfAbsent(new Item(i), key -> new Item(findValue(map, key)));
848 +            }
849 +            fail("recursive computeIfAbsent should throw IllegalStateException");
850 +        } catch (IllegalStateException success) {}
851      }
852  
853 <    
853 >    private static Item findValue(ConcurrentHashMap<Item, Item> map,
854 >                                  Item key) {
855 >        return (key.value % 5 == 0) ?  key :
856 >            map.computeIfAbsent(new Item(key.value + 1), k -> new Item(findValue(map, k)));
857 >    }
858   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines