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

Comparing jsr166/src/test/tck/ThreadLocalRandomTest.java (file contents):
Revision 1.7 by jsr166, Wed Aug 25 00:07:03 2010 UTC vs.
Revision 1.28 by jsr166, Sun Jan 7 22:59:18 2018 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   */
6 import junit.framework.*;
7 import java.util.concurrent.*;
8 import java.util.*;
6  
7 + import java.util.concurrent.ThreadLocalRandom;
8 + import java.util.concurrent.atomic.AtomicLong;
9 + import java.util.concurrent.atomic.AtomicReference;
10 +
11 + import junit.framework.Test;
12 + import junit.framework.TestSuite;
13  
14   public class ThreadLocalRandomTest extends JSR166TestCase {
15  
16      public static void main(String[] args) {
17 <        junit.textui.TestRunner.run(suite());
17 >        main(suite(), args);
18      }
19      public static Test suite() {
20          return new TestSuite(ThreadLocalRandomTest.class);
21      }
22  
23 <    /**
23 >    /*
24       * Testing coverage notes:
25       *
26       * We don't test randomness properties, but only that repeated
# Line 26 | Line 29 | public class ThreadLocalRandomTest exten
29       * across multiples of primes.
30       */
31  
32 <    //
32 >    // max numbers of calls to detect getting stuck on one value
33      static final int NCALLS = 10000;
34  
35      // max sampled int bound
36      static final int MAX_INT_BOUND = (1 << 28);
37  
38 <    // Max sampled long bound
38 >    // max sampled long bound
39      static final long MAX_LONG_BOUND = (1L << 42);
40  
41 +    // Number of replications for other checks
42 +    static final int REPS = 20;
43 +
44      /**
45       * setSeed throws UnsupportedOperationException
46       */
# Line 46 | Line 52 | public class ThreadLocalRandomTest exten
52      }
53  
54      /**
55 <     * Repeated calls to nextInt produce at least one different result
55 >     * Repeated calls to next (only accessible via reflection) produce
56 >     * at least two distinct results, and repeated calls produce all
57 >     * possible values.
58 >     */
59 >    public void testNext() throws ReflectiveOperationException {
60 >        // Inhibit "An illegal reflective access operation has occurred"
61 >        if (!testImplementationDetails) return;
62 >
63 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
64 >        final java.lang.reflect.Method m;
65 >        try {
66 >            m = ThreadLocalRandom.class.getDeclaredMethod(
67 >                    "next", new Class[] { int.class });
68 >            m.setAccessible(true);
69 >        } catch (SecurityException acceptable) {
70 >            // Security manager may deny access
71 >            return;
72 >        } catch (Exception ex) {
73 >            // jdk9 module system may deny access
74 >            if (ex.getClass().getSimpleName()
75 >                .equals("InaccessibleObjectException"))
76 >                return;
77 >            throw ex;
78 >        }
79 >
80 >        int i;
81 >        {
82 >            int val = new java.util.Random().nextInt(4);
83 >            for (i = 0; i < NCALLS; i++) {
84 >                int q = (int) m.invoke(rnd, new Object[] { 2 });
85 >                if (val == q) break;
86 >            }
87 >            assertTrue(i < NCALLS);
88 >        }
89 >
90 >        {
91 >            int r = (int) m.invoke(rnd, new Object[] { 3 });
92 >            for (i = 0; i < NCALLS; i++) {
93 >                int q = (int) m.invoke(rnd, new Object[] { 3 });
94 >                assertTrue(q < (1<<3));
95 >                if (r != q) break;
96 >            }
97 >            assertTrue(i < NCALLS);
98 >        }
99 >    }
100 >
101 >    /**
102 >     * Repeated calls to nextInt produce at least two distinct results
103       */
104      public void testNextInt() {
105          int f = ThreadLocalRandom.current().nextInt();
# Line 57 | Line 110 | public class ThreadLocalRandomTest exten
110      }
111  
112      /**
113 <     * Repeated calls to nextLong produce at least one different result
113 >     * Repeated calls to nextLong produce at least two distinct results
114       */
115      public void testNextLong() {
116          long f = ThreadLocalRandom.current().nextLong();
# Line 67 | Line 120 | public class ThreadLocalRandomTest exten
120          assertTrue(i < NCALLS);
121      }
122  
70
123      /**
124 <     * Repeated calls to nextBoolean produce at least one different result
124 >     * Repeated calls to nextBoolean produce at least two distinct results
125       */
126      public void testNextBoolean() {
127          boolean f = ThreadLocalRandom.current().nextBoolean();
# Line 80 | Line 132 | public class ThreadLocalRandomTest exten
132      }
133  
134      /**
135 <     * Repeated calls to nextFloat produce at least one different result
135 >     * Repeated calls to nextFloat produce at least two distinct results
136       */
137      public void testNextFloat() {
138          float f = ThreadLocalRandom.current().nextFloat();
# Line 91 | Line 143 | public class ThreadLocalRandomTest exten
143      }
144  
145      /**
146 <     * Repeated calls to nextDouble produce at least one different result
146 >     * Repeated calls to nextDouble produce at least two distinct results
147       */
148      public void testNextDouble() {
149          double f = ThreadLocalRandom.current().nextDouble();
150 <        double i = 0;
150 >        int i = 0;
151          while (i < NCALLS && ThreadLocalRandom.current().nextDouble() == f)
152              ++i;
153          assertTrue(i < NCALLS);
154      }
155  
156      /**
157 <     * Repeated calls to nextGaussian produce at least one different result
157 >     * Repeated calls to nextGaussian produce at least two distinct results
158       */
159      public void testNextGaussian() {
160          double f = ThreadLocalRandom.current().nextGaussian();
# Line 112 | Line 164 | public class ThreadLocalRandomTest exten
164          assertTrue(i < NCALLS);
165      }
166  
115
167      /**
168 <     * nextInt(negative) throws IllegalArgumentException;
168 >     * nextInt(non-positive) throws IllegalArgumentException
169       */
170 <    public void testNextIntBoundedNeg() {
171 <        try {
172 <            int f = ThreadLocalRandom.current().nextInt(-17);
173 <            shouldThrow();
174 <        } catch (IllegalArgumentException success) {}
170 >    public void testNextIntBoundNonPositive() {
171 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
172 >        for (int bound : new int[] { 0, -17, Integer.MIN_VALUE }) {
173 >            try {
174 >                rnd.nextInt(bound);
175 >                shouldThrow();
176 >            } catch (IllegalArgumentException success) {}
177 >        }
178      }
179  
180      /**
181 <     * nextInt(least >= bound) throws IllegalArgumentException;
181 >     * nextInt(least >= bound) throws IllegalArgumentException
182       */
183      public void testNextIntBadBounds() {
184 <        try {
185 <            int f = ThreadLocalRandom.current().nextInt(17, 2);
186 <            shouldThrow();
187 <        } catch (IllegalArgumentException success) {}
184 >        int[][] badBoundss = {
185 >            { 17, 2 },
186 >            { -42, -42 },
187 >            { Integer.MAX_VALUE, Integer.MIN_VALUE },
188 >        };
189 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
190 >        for (int[] badBounds : badBoundss) {
191 >            try {
192 >                rnd.nextInt(badBounds[0], badBounds[1]);
193 >                shouldThrow();
194 >            } catch (IllegalArgumentException success) {}
195 >        }
196      }
197  
136
198      /**
199       * nextInt(bound) returns 0 <= value < bound;
200 <     * repeated calls produce at least one different result
200 >     * repeated calls produce at least two distinct results
201       */
202      public void testNextIntBounded() {
203          // sample bound space across prime number increments
# Line 154 | Line 215 | public class ThreadLocalRandomTest exten
215          }
216      }
217  
157
218      /**
219       * nextInt(least, bound) returns least <= value < bound;
220 <     * repeated calls produce at least one different result
220 >     * repeated calls produce at least two distinct results
221       */
222      public void testNextIntBounded2() {
223          for (int least = -15485863; least < MAX_INT_BOUND; least += 524959) {
# Line 177 | Line 237 | public class ThreadLocalRandomTest exten
237      }
238  
239      /**
240 <     * nextLong(negative) throws IllegalArgumentException;
240 >     * nextLong(non-positive) throws IllegalArgumentException
241       */
242 <    public void testNextLongBoundedNeg() {
243 <        try {
244 <            long f = ThreadLocalRandom.current().nextLong(-17);
245 <            shouldThrow();
246 <        } catch (IllegalArgumentException success) {}
242 >    public void testNextLongBoundNonPositive() {
243 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
244 >        for (long bound : new long[] { 0L, -17L, Long.MIN_VALUE }) {
245 >            try {
246 >                rnd.nextLong(bound);
247 >                shouldThrow();
248 >            } catch (IllegalArgumentException success) {}
249 >        }
250      }
251  
252      /**
253 <     * nextLong(least >= bound) throws IllegalArgumentException;
253 >     * nextLong(least >= bound) throws IllegalArgumentException
254       */
255      public void testNextLongBadBounds() {
256 <        try {
257 <            long f = ThreadLocalRandom.current().nextLong(17, 2);
258 <            shouldThrow();
259 <        } catch (IllegalArgumentException success) {}
256 >        long[][] badBoundss = {
257 >            { 17L, 2L },
258 >            { -42L, -42L },
259 >            { Long.MAX_VALUE, Long.MIN_VALUE },
260 >        };
261 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
262 >        for (long[] badBounds : badBoundss) {
263 >            try {
264 >                rnd.nextLong(badBounds[0], badBounds[1]);
265 >                shouldThrow();
266 >            } catch (IllegalArgumentException success) {}
267 >        }
268      }
269  
270      /**
271       * nextLong(bound) returns 0 <= value < bound;
272 <     * repeated calls produce at least one different result
272 >     * repeated calls produce at least two distinct results
273       */
274      public void testNextLongBounded() {
275          for (long bound = 2; bound < MAX_LONG_BOUND; bound += 15485863) {
# Line 217 | Line 288 | public class ThreadLocalRandomTest exten
288  
289      /**
290       * nextLong(least, bound) returns least <= value < bound;
291 <     * repeated calls produce at least one different result
291 >     * repeated calls produce at least two distinct results
292       */
293      public void testNextLongBounded2() {
294          for (long least = -86028121; least < MAX_LONG_BOUND; least += 982451653L) {
# Line 236 | Line 307 | public class ThreadLocalRandomTest exten
307          }
308      }
309  
310 +    /**
311 +     * nextDouble(non-positive) throws IllegalArgumentException
312 +     */
313 +    public void testNextDoubleBoundNonPositive() {
314 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
315 +        double[] badBounds = {
316 +            0.0d,
317 +            -17.0d,
318 +            -Double.MIN_VALUE,
319 +            Double.NEGATIVE_INFINITY,
320 +            Double.NaN,
321 +        };
322 +        for (double bound : badBounds) {
323 +            try {
324 +                rnd.nextDouble(bound);
325 +                shouldThrow();
326 +            } catch (IllegalArgumentException success) {}
327 +        }
328 +    }
329  
330      /**
331       * nextDouble(least, bound) returns least <= value < bound;
332 <     * repeated calls produce at least one different result
332 >     * repeated calls produce at least two distinct results
333       */
334      public void testNextDoubleBounded2() {
335          for (double least = 0.0001; least < 1.0e20; least *= 8) {
# Line 258 | Line 348 | public class ThreadLocalRandomTest exten
348          }
349      }
350  
351 +    /**
352 +     * Different threads produce different pseudo-random sequences
353 +     */
354 +    public void testDifferentSequences() {
355 +        // Don't use main thread's ThreadLocalRandom - it is likely to
356 +        // be polluted by previous tests.
357 +        final AtomicReference<ThreadLocalRandom> threadLocalRandom =
358 +            new AtomicReference<>();
359 +        final AtomicLong rand = new AtomicLong();
360 +
361 +        long firstRand = 0;
362 +        ThreadLocalRandom firstThreadLocalRandom = null;
363 +
364 +        Runnable getRandomState = new CheckedRunnable() {
365 +            public void realRun() {
366 +                ThreadLocalRandom current = ThreadLocalRandom.current();
367 +                assertSame(current, ThreadLocalRandom.current());
368 +                // test bug: the following is not guaranteed and not true in JDK8
369 +                //                assertNotSame(current, threadLocalRandom.get());
370 +                rand.set(current.nextLong());
371 +                threadLocalRandom.set(current);
372 +            }};
373 +
374 +        Thread first = newStartedThread(getRandomState);
375 +        awaitTermination(first);
376 +        firstRand = rand.get();
377 +        firstThreadLocalRandom = threadLocalRandom.get();
378 +
379 +        for (int i = 0; i < NCALLS; i++) {
380 +            Thread t = newStartedThread(getRandomState);
381 +            awaitTermination(t);
382 +            if (firstRand != rand.get())
383 +                return;
384 +        }
385 +        fail("all threads generate the same pseudo-random sequence");
386 +    }
387 +
388 +    /**
389 +     * Repeated calls to nextBytes produce at least values of different signs for every byte
390 +     */
391 +    public void testNextBytes() {
392 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
393 +        int n = rnd.nextInt(1, 20);
394 +        byte[] bytes = new byte[n];
395 +        outer:
396 +        for (int i = 0; i < n; i++) {
397 +            for (int tries = NCALLS; tries-->0; ) {
398 +                byte before = bytes[i];
399 +                rnd.nextBytes(bytes);
400 +                byte after = bytes[i];
401 +                if (after * before < 0)
402 +                    continue outer;
403 +            }
404 +            fail("not enough variation in random bytes");
405 +        }
406 +    }
407 +
408 +    /**
409 +     * Filling an empty array with random bytes succeeds without effect.
410 +     */
411 +    public void testNextBytes_emptyArray() {
412 +        ThreadLocalRandom.current().nextBytes(new byte[0]);
413 +    }
414 +
415 +    public void testNextBytes_nullArray() {
416 +        try {
417 +            ThreadLocalRandom.current().nextBytes(null);
418 +            shouldThrow();
419 +        } catch (NullPointerException success) {}
420 +    }
421  
422   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines