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.19 by jsr166, Sat Nov 21 17:38:05 2009 UTC vs.
Revision 1.37 by jsr166, Mon Jul 22 15:55:43 2013 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10   import java.util.*;
11 < import java.util.concurrent.*;
12 < import java.util.Enumeration;
13 < import java.io.*;
11 > import java.util.concurrent.ConcurrentHashMap;
12  
13   public class ConcurrentHashMapTest extends JSR166TestCase {
14      public static void main(String[] args) {
15 <        junit.textui.TestRunner.run (suite());
15 >        junit.textui.TestRunner.run(suite());
16      }
17      public static Test suite() {
18          return new TestSuite(ConcurrentHashMapTest.class);
19      }
20  
21      /**
22 <     * Create a map from Integers 1-5 to Strings "A"-"E".
22 >     * Returns a new map from Integers 1-5 to Strings "A"-"E".
23       */
24 <    private static ConcurrentHashMap map5() {
25 <        ConcurrentHashMap map = new ConcurrentHashMap(5);
24 >    private static ConcurrentHashMap<Integer, String> map5() {
25 >        ConcurrentHashMap map = new ConcurrentHashMap<Integer, String>(5);
26          assertTrue(map.isEmpty());
27          map.put(one, "A");
28          map.put(two, "B");
# Line 36 | Line 34 | public class ConcurrentHashMapTest exten
34          return map;
35      }
36  
37 +    /** Re-implement Integer.compare for old java versions */
38 +    static int compare(int x, int y) { return x < y ? -1 : x > y ? 1 : 0; }
39 +
40 +    // classes for testing Comparable fallbacks
41 +    static class BI implements Comparable<BI> {
42 +        private final int value;
43 +        BI(int value) { this.value = value; }
44 +        public int compareTo(BI other) {
45 +            return compare(value, other.value);
46 +        }
47 +        public boolean equals(Object x) {
48 +            return (x instanceof BI) && ((BI)x).value == value;
49 +        }
50 +        public int hashCode() { return 42; }
51 +    }
52 +    static class CI extends BI { CI(int value) { super(value); } }
53 +    static class DI extends BI { DI(int value) { super(value); } }
54 +
55 +    static class BS implements Comparable<BS> {
56 +        private final String value;
57 +        BS(String value) { this.value = value; }
58 +        public int compareTo(BS other) {
59 +            return value.compareTo(other.value);
60 +        }
61 +        public boolean equals(Object x) {
62 +            return (x instanceof BS) && value.equals(((BS)x).value);
63 +        }
64 +        public int hashCode() { return 42; }
65 +    }
66 +
67 +    static class LexicographicList<E extends Comparable<E>> extends ArrayList<E>
68 +        implements Comparable<LexicographicList<E>> {
69 +        LexicographicList(Collection<E> c) { super(c); }
70 +        LexicographicList(E e) { super(Collections.singleton(e)); }
71 +        public int compareTo(LexicographicList<E> other) {
72 +            int common = Math.min(size(), other.size());
73 +            int r = 0;
74 +            for (int i = 0; i < common; i++) {
75 +                if ((r = get(i).compareTo(other.get(i))) != 0)
76 +                    break;
77 +            }
78 +            if (r == 0)
79 +                r = compare(size(), other.size());
80 +            return r;
81 +        }
82 +        private static final long serialVersionUID = 0;
83 +    }
84 +
85 +    static class CollidingObject {
86 +        final String value;
87 +        CollidingObject(final String value) { this.value = value; }
88 +        public int hashCode() { return this.value.hashCode() & 1; }
89 +        public boolean equals(final Object obj) {
90 +            return (obj instanceof CollidingObject) && ((CollidingObject)obj).value.equals(value);
91 +        }
92 +    }
93 +
94 +    static class ComparableCollidingObject extends CollidingObject implements Comparable<ComparableCollidingObject> {
95 +        ComparableCollidingObject(final String value) { super(value); }
96 +        public int compareTo(final ComparableCollidingObject o) {
97 +            return value.compareTo(o.value);
98 +        }
99 +    }
100 +
101      /**
102 <     *  clear removes all pairs
102 >     * Inserted elements that are subclasses of the same Comparable
103 >     * class are found.
104 >     */
105 >    public void testComparableFamily() {
106 >        ConcurrentHashMap<BI, Boolean> m =
107 >            new ConcurrentHashMap<BI, Boolean>();
108 >        for (int i = 0; i < 1000; i++) {
109 >            assertTrue(m.put(new CI(i), true) == null);
110 >        }
111 >        for (int i = 0; i < 1000; i++) {
112 >            assertTrue(m.containsKey(new CI(i)));
113 >            assertTrue(m.containsKey(new DI(i)));
114 >        }
115 >    }
116 >
117 >    /**
118 >     * Elements of classes with erased generic type parameters based
119 >     * on Comparable can be inserted and found.
120 >     */
121 >    public void testGenericComparable() {
122 >        ConcurrentHashMap<Object, Boolean> m =
123 >            new ConcurrentHashMap<Object, Boolean>();
124 >        for (int i = 0; i < 1000; i++) {
125 >            BI bi = new BI(i);
126 >            BS bs = new BS(String.valueOf(i));
127 >            LexicographicList<BI> bis = new LexicographicList<BI>(bi);
128 >            LexicographicList<BS> bss = new LexicographicList<BS>(bs);
129 >            assertTrue(m.putIfAbsent(bis, true) == null);
130 >            assertTrue(m.containsKey(bis));
131 >            if (m.putIfAbsent(bss, true) == null)
132 >                assertTrue(m.containsKey(bss));
133 >            assertTrue(m.containsKey(bis));
134 >        }
135 >        for (int i = 0; i < 1000; i++) {
136 >            assertTrue(m.containsKey(new ArrayList(Collections.singleton(new BI(i)))));
137 >        }
138 >    }
139 >
140 >    /**
141 >     * Elements of non-comparable classes equal to those of classes
142 >     * with erased generic type parameters based on Comparable can be
143 >     * inserted and found.
144 >     */
145 >    public void testGenericComparable2() {
146 >        ConcurrentHashMap<Object, Boolean> m =
147 >            new ConcurrentHashMap<Object, Boolean>();
148 >        for (int i = 0; i < 1000; i++) {
149 >            m.put(new ArrayList(Collections.singleton(new BI(i))), true);
150 >        }
151 >
152 >        for (int i = 0; i < 1000; i++) {
153 >            LexicographicList<BI> bis = new LexicographicList<BI>(new BI(i));
154 >            assertTrue(m.containsKey(bis));
155 >        }
156 >    }
157 >
158 >    /**
159 >     * Mixtures of instances of comparable and non-comparable classes
160 >     * can be inserted and found.
161 >     */
162 >    public void testMixedComparable() {
163 >        int size = 10000;
164 >        ConcurrentHashMap<Object, Object> map =
165 >            new ConcurrentHashMap<Object, Object>();
166 >        Random rng = new Random(1370014958369218000L);
167 >        for (int i = 0; i < size; i++) {
168 >            Object x;
169 >            switch (rng.nextInt(4)) {
170 >            case 0:
171 >                x = new Object();
172 >                break;
173 >            case 1:
174 >                x = new CollidingObject(Integer.toString(i));
175 >                break;
176 >            default:
177 >                x = new ComparableCollidingObject(Integer.toString(i));
178 >            }
179 >            assertNull(map.put(x, x));
180 >        }
181 >        int count = 0;
182 >        for (Object k : map.keySet()) {
183 >            assertEquals(map.get(k), k);
184 >            ++count;
185 >        }
186 >        assertEquals(count, size);
187 >        assertEquals(map.size(), size);
188 >        for (Object k : map.keySet()) {
189 >            assertEquals(map.put(k, k), k);
190 >        }
191 >    }
192 >
193 >    /**
194 >     * clear removes all pairs
195       */
196      public void testClear() {
197          ConcurrentHashMap map = map5();
198          map.clear();
199 <        assertEquals(map.size(), 0);
199 >        assertEquals(0, map.size());
200      }
201  
202      /**
203 <     *  Maps with same contents are equal
203 >     * Maps with same contents are equal
204       */
205      public void testEquals() {
206          ConcurrentHashMap map1 = map5();
# Line 59 | Line 213 | public class ConcurrentHashMapTest exten
213      }
214  
215      /**
216 <     *  contains returns true for contained value
216 >     * hashCode() equals sum of each key.hashCode ^ value.hashCode
217 >     */
218 >    public void testHashCode() {
219 >        ConcurrentHashMap<Integer,String> map = map5();
220 >        int sum = 0;
221 >        for (Map.Entry<Integer,String> e : map.entrySet())
222 >            sum += e.getKey().hashCode() ^ e.getValue().hashCode();
223 >        assertEquals(sum, map.hashCode());
224 >    }
225 >
226 >    /**
227 >     * contains returns true for contained value
228       */
229      public void testContains() {
230          ConcurrentHashMap map = map5();
# Line 68 | Line 233 | public class ConcurrentHashMapTest exten
233      }
234  
235      /**
236 <     *  containsKey returns true for contained key
236 >     * containsKey returns true for contained key
237       */
238      public void testContainsKey() {
239          ConcurrentHashMap map = map5();
# Line 77 | Line 242 | public class ConcurrentHashMapTest exten
242      }
243  
244      /**
245 <     *  containsValue returns true for held values
245 >     * containsValue returns true for held values
246       */
247      public void testContainsValue() {
248          ConcurrentHashMap map = map5();
# Line 86 | Line 251 | public class ConcurrentHashMapTest exten
251      }
252  
253      /**
254 <     *   enumeration returns an enumeration containing the correct
255 <     *   elements
254 >     * enumeration returns an enumeration containing the correct
255 >     * elements
256       */
257      public void testEnumeration() {
258          ConcurrentHashMap map = map5();
# Line 101 | Line 266 | public class ConcurrentHashMapTest exten
266      }
267  
268      /**
269 <     *  get returns the correct element at the given key,
270 <     *  or null if not present
269 >     * get returns the correct element at the given key,
270 >     * or null if not present
271       */
272      public void testGet() {
273          ConcurrentHashMap map = map5();
# Line 112 | Line 277 | public class ConcurrentHashMapTest exten
277      }
278  
279      /**
280 <     *  isEmpty is true of empty map and false for non-empty
280 >     * isEmpty is true of empty map and false for non-empty
281       */
282      public void testIsEmpty() {
283          ConcurrentHashMap empty = new ConcurrentHashMap();
# Line 122 | Line 287 | public class ConcurrentHashMapTest exten
287      }
288  
289      /**
290 <     *   keys returns an enumeration containing all the keys from the map
290 >     * keys returns an enumeration containing all the keys from the map
291       */
292      public void testKeys() {
293          ConcurrentHashMap map = map5();
# Line 136 | Line 301 | public class ConcurrentHashMapTest exten
301      }
302  
303      /**
304 <     *   keySet returns a Set containing all the keys
304 >     * keySet returns a Set containing all the keys
305       */
306      public void testKeySet() {
307          ConcurrentHashMap map = map5();
# Line 150 | Line 315 | public class ConcurrentHashMapTest exten
315      }
316  
317      /**
318 <     *  keySet.toArray returns contains all keys
318 >     * keySet.toArray returns contains all keys
319       */
320      public void testKeySetToArray() {
321          ConcurrentHashMap map = map5();
# Line 163 | Line 328 | public class ConcurrentHashMapTest exten
328      }
329  
330      /**
331 <     *  Values.toArray contains all values
331 >     * Values.toArray contains all values
332       */
333      public void testValuesToArray() {
334          ConcurrentHashMap map = map5();
# Line 179 | Line 344 | public class ConcurrentHashMapTest exten
344      }
345  
346      /**
347 <     *  entrySet.toArray contains all entries
347 >     * entrySet.toArray contains all entries
348       */
349      public void testEntrySetToArray() {
350          ConcurrentHashMap map = map5();
# Line 226 | Line 391 | public class ConcurrentHashMapTest exten
391      }
392  
393      /**
394 <     *   putAll  adds all key-value pairs from the given map
394 >     * putAll adds all key-value pairs from the given map
395       */
396      public void testPutAll() {
397          ConcurrentHashMap empty = new ConcurrentHashMap();
# Line 241 | Line 406 | public class ConcurrentHashMapTest exten
406      }
407  
408      /**
409 <     *   putIfAbsent works when the given key is not present
409 >     * putIfAbsent works when the given key is not present
410       */
411      public void testPutIfAbsent() {
412          ConcurrentHashMap map = map5();
# Line 250 | Line 415 | public class ConcurrentHashMapTest exten
415      }
416  
417      /**
418 <     *   putIfAbsent does not add the pair if the key is already present
418 >     * putIfAbsent does not add the pair if the key is already present
419       */
420      public void testPutIfAbsent2() {
421          ConcurrentHashMap map = map5();
# Line 258 | Line 423 | public class ConcurrentHashMapTest exten
423      }
424  
425      /**
426 <     *   replace fails when the given key is not present
426 >     * replace fails when the given key is not present
427       */
428      public void testReplace() {
429          ConcurrentHashMap map = map5();
# Line 267 | Line 432 | public class ConcurrentHashMapTest exten
432      }
433  
434      /**
435 <     *   replace succeeds if the key is already present
435 >     * replace succeeds if the key is already present
436       */
437      public void testReplace2() {
438          ConcurrentHashMap map = map5();
# Line 275 | Line 440 | public class ConcurrentHashMapTest exten
440          assertEquals("Z", map.get(one));
441      }
442  
278
443      /**
444       * replace value fails when the given key not mapped to expected value
445       */
# Line 296 | Line 460 | public class ConcurrentHashMapTest exten
460          assertEquals("Z", map.get(one));
461      }
462  
299
463      /**
464 <     *   remove removes the correct key-value pair from the map
464 >     * remove removes the correct key-value pair from the map
465       */
466      public void testRemove() {
467          ConcurrentHashMap map = map5();
# Line 318 | Line 481 | public class ConcurrentHashMapTest exten
481          map.remove(four, "A");
482          assertEquals(4, map.size());
483          assertTrue(map.containsKey(four));
321
484      }
485  
486      /**
487 <     *   size returns the correct values
487 >     * size returns the correct values
488       */
489      public void testSize() {
490          ConcurrentHashMap map = map5();
# Line 338 | Line 500 | public class ConcurrentHashMapTest exten
500          ConcurrentHashMap map = map5();
501          String s = map.toString();
502          for (int i = 1; i <= 5; ++i) {
503 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
503 >            assertTrue(s.contains(String.valueOf(i)));
504          }
505      }
506  
507      // Exception tests
508  
509      /**
510 <     * Cannot create with negative capacity
510 >     * Cannot create with only negative capacity
511       */
512      public void testConstructor1() {
513          try {
514 <            new ConcurrentHashMap(-1,0,1);
514 >            new ConcurrentHashMap(-1);
515              shouldThrow();
516          } catch (IllegalArgumentException success) {}
517      }
518  
519      /**
520 <     * Cannot create with negative concurrency level
521 <     */
520 >     * Constructor (initialCapacity, loadFactor) throws
521 >     * IllegalArgumentException if either argument is negative
522 >      */
523      public void testConstructor2() {
524          try {
525 <            new ConcurrentHashMap(1,0,-1);
525 >            new ConcurrentHashMap(-1, .75f);
526              shouldThrow();
527 <        } catch (IllegalArgumentException success) {}
527 >        } catch (IllegalArgumentException e) {}
528 >
529 >        try {
530 >            new ConcurrentHashMap(16, -1);
531 >            shouldThrow();
532 >        } catch (IllegalArgumentException e) {}
533      }
534  
535      /**
536 <     * Cannot create with only negative capacity
536 >     * Constructor (initialCapacity, loadFactor, concurrencyLevel)
537 >     * throws IllegalArgumentException if any argument is negative
538       */
539      public void testConstructor3() {
540          try {
541 <            new ConcurrentHashMap(-1);
541 >            new ConcurrentHashMap(-1, .75f, 1);
542              shouldThrow();
543 <        } catch (IllegalArgumentException success) {}
543 >        } catch (IllegalArgumentException e) {}
544 >
545 >        try {
546 >            new ConcurrentHashMap(16, -1, 1);
547 >            shouldThrow();
548 >        } catch (IllegalArgumentException e) {}
549 >
550 >        try {
551 >            new ConcurrentHashMap(16, .75f, -1);
552 >            shouldThrow();
553 >        } catch (IllegalArgumentException e) {}
554      }
555  
556      /**
557 +     * ConcurrentHashMap(map) throws NullPointerException if the given
558 +     * map is null
559 +     */
560 +    public void testConstructor4() {
561 +        try {
562 +            new ConcurrentHashMap(null);
563 +            shouldThrow();
564 +        } catch (NullPointerException e) {}
565 +    }
566 +
567 +    /**
568 +     * ConcurrentHashMap(map) creates a new map with the same mappings
569 +     * as the given map
570 +     */
571 +    public void testConstructor5() {
572 +        ConcurrentHashMap map1 = map5();
573 +        ConcurrentHashMap map2 = new ConcurrentHashMap(map5());
574 +        assertTrue(map2.equals(map1));
575 +        map2.put(one, "F");
576 +        assertFalse(map2.equals(map1));
577 +    }
578 +
579 +
580 +    /**
581       * get(null) throws NPE
582       */
583      public void testGet_NullPointerException() {
# Line 484 | Line 687 | public class ConcurrentHashMapTest exten
687          } catch (NullPointerException success) {}
688      }
689  
487
690      /**
691       * replace(x, null) throws NPE
692       */
# Line 518 | Line 720 | public class ConcurrentHashMapTest exten
720          } catch (NullPointerException success) {}
721      }
722  
521
723      /**
724       * remove(null) throws NPE
725       */
# Line 556 | Line 757 | public class ConcurrentHashMapTest exten
757       * A deserialized map equals original
758       */
759      public void testSerialization() throws Exception {
760 <        ConcurrentHashMap q = map5();
760 >        Map x = map5();
761 >        Map y = serialClone(x);
762  
763 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
764 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
765 <        out.writeObject(q);
766 <        out.close();
565 <
566 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
567 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
568 <        ConcurrentHashMap r = (ConcurrentHashMap)in.readObject();
569 <        assertEquals(q.size(), r.size());
570 <        assertTrue(q.equals(r));
571 <        assertTrue(r.equals(q));
763 >        assertNotSame(x, y);
764 >        assertEquals(x.size(), y.size());
765 >        assertEquals(x, y);
766 >        assertEquals(y, x);
767      }
768  
574
769      /**
770       * SetValue of an EntrySet entry sets value in the map.
771       */
# Line 583 | Line 777 | public class ConcurrentHashMapTest exten
777              map.put(new Integer(i), new Integer(i));
778          assertFalse(map.isEmpty());
779          Map.Entry entry1 = (Map.Entry)map.entrySet().iterator().next();
780 <
781 <        // assert that entry1 is not 16
782 <        assertTrue("entry is 16, test not valid",
783 <                   !entry1.getKey().equals(new Integer(16)));
784 <
785 <        // remove 16 (a different key) from map
786 <        // which just happens to cause entry1 to be cloned in map
787 <        map.remove(new Integer(16));
788 <        entry1.setValue("XYZ");
595 <        assertTrue(map.containsValue("XYZ")); // fails
780 >        // Unless it happens to be first (in which case remainder of
781 >        // test is skipped), remove a possibly-colliding key from map
782 >        // which, under some implementations, may cause entry1 to be
783 >        // cloned in map
784 >        if (!entry1.getKey().equals(new Integer(16))) {
785 >            map.remove(new Integer(16));
786 >            entry1.setValue("XYZ");
787 >            assertTrue(map.containsValue("XYZ")); // fails if write-through broken
788 >        }
789      }
790  
791   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines