6 |
|
import junit.framework.*; |
7 |
|
import java.util.*; |
8 |
|
import java.util.concurrent.ThreadLocalRandom; |
9 |
+ |
import java.util.concurrent.atomic.AtomicLong; |
10 |
+ |
import java.util.concurrent.atomic.AtomicReference; |
11 |
|
|
12 |
|
public class ThreadLocalRandomTest extends JSR166TestCase { |
13 |
|
|
254 |
|
} |
255 |
|
} |
256 |
|
|
257 |
+ |
/** |
258 |
+ |
* Different threads produce different pseudo-random sequences |
259 |
+ |
*/ |
260 |
+ |
public void testDifferentSequences() { |
261 |
+ |
// Don't use main thread's ThreadLocalRandom - it is likely to |
262 |
+ |
// be polluted by previous tests. |
263 |
+ |
final AtomicReference<ThreadLocalRandom> threadLocalRandom = |
264 |
+ |
new AtomicReference<ThreadLocalRandom>(); |
265 |
+ |
final AtomicLong rand = new AtomicLong(); |
266 |
+ |
|
267 |
+ |
long firstRand = 0; |
268 |
+ |
ThreadLocalRandom firstThreadLocalRandom = null; |
269 |
+ |
|
270 |
+ |
final CheckedRunnable getRandomState = new CheckedRunnable() { |
271 |
+ |
public void realRun() { |
272 |
+ |
ThreadLocalRandom current = ThreadLocalRandom.current(); |
273 |
+ |
assertSame(current, ThreadLocalRandom.current()); |
274 |
+ |
assertNotSame(current, threadLocalRandom.get()); |
275 |
+ |
rand.set(current.nextLong()); |
276 |
+ |
threadLocalRandom.set(current); |
277 |
+ |
}}; |
278 |
+ |
|
279 |
+ |
Thread first = newStartedThread(getRandomState); |
280 |
+ |
awaitTermination(first); |
281 |
+ |
firstRand = rand.get(); |
282 |
+ |
firstThreadLocalRandom = threadLocalRandom.get(); |
283 |
+ |
|
284 |
+ |
for (int i = 0; i < NCALLS; i++) { |
285 |
+ |
Thread t = newStartedThread(getRandomState); |
286 |
+ |
awaitTermination(t); |
287 |
+ |
if (firstRand != rand.get()) |
288 |
+ |
return; |
289 |
+ |
} |
290 |
+ |
fail("all threads generate the same pseudo-random sequence"); |
291 |
+ |
} |
292 |
+ |
|
293 |
|
} |