--- jsr166/src/test/tck/ThreadLocalRandomTest.java 2017/09/19 20:10:49 1.25 +++ jsr166/src/test/tck/ThreadLocalRandomTest.java 2020/08/12 17:39:43 1.30 @@ -63,8 +63,7 @@ public class ThreadLocalRandomTest exten ThreadLocalRandom rnd = ThreadLocalRandom.current(); final java.lang.reflect.Method m; try { - m = ThreadLocalRandom.class.getDeclaredMethod( - "next", new Class[] { int.class }); + m = ThreadLocalRandom.class.getDeclaredMethod("next", int.class); m.setAccessible(true); } catch (SecurityException acceptable) { // Security manager may deny access @@ -355,34 +354,65 @@ public class ThreadLocalRandomTest exten // Don't use main thread's ThreadLocalRandom - it is likely to // be polluted by previous tests. final AtomicReference threadLocalRandom = - new AtomicReference(); + new AtomicReference<>(); final AtomicLong rand = new AtomicLong(); - long firstRand = 0; - ThreadLocalRandom firstThreadLocalRandom = null; - Runnable getRandomState = new CheckedRunnable() { public void realRun() { ThreadLocalRandom current = ThreadLocalRandom.current(); assertSame(current, ThreadLocalRandom.current()); - // test bug: the following is not guaranteed and not true in JDK8 - // assertNotSame(current, threadLocalRandom.get()); rand.set(current.nextLong()); threadLocalRandom.set(current); }}; - Thread first = newStartedThread(getRandomState); - awaitTermination(first); - firstRand = rand.get(); - firstThreadLocalRandom = threadLocalRandom.get(); + awaitTermination(newStartedThread(getRandomState)); + long firstRand = rand.get(); + ThreadLocalRandom firstThreadLocalRandom = threadLocalRandom.get(); + assertNotNull(firstThreadLocalRandom); for (int i = 0; i < NCALLS; i++) { - Thread t = newStartedThread(getRandomState); - awaitTermination(t); + awaitTermination(newStartedThread(getRandomState)); + if (testImplementationDetails) + // ThreadLocalRandom has been a singleton since jdk8. + assertSame(firstThreadLocalRandom, threadLocalRandom.get()); if (firstRand != rand.get()) return; } fail("all threads generate the same pseudo-random sequence"); } + /** + * Repeated calls to nextBytes produce at least values of different signs for every byte + */ + public void testNextBytes() { + ThreadLocalRandom rnd = ThreadLocalRandom.current(); + int n = rnd.nextInt(1, 20); + byte[] bytes = new byte[n]; + outer: + for (int i = 0; i < n; i++) { + for (int tries = NCALLS; tries-->0; ) { + byte before = bytes[i]; + rnd.nextBytes(bytes); + byte after = bytes[i]; + if (after * before < 0) + continue outer; + } + fail("not enough variation in random bytes"); + } + } + + /** + * Filling an empty array with random bytes succeeds without effect. + */ + public void testNextBytes_emptyArray() { + ThreadLocalRandom.current().nextBytes(new byte[0]); + } + + public void testNextBytes_nullArray() { + try { + ThreadLocalRandom.current().nextBytes(null); + shouldThrow(); + } catch (NullPointerException success) {} + } + }