Path: blob/master/test/jdk/java/util/Random/DistinctSeeds.java
41149 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation.6*7* This code is distributed in the hope that it will be useful, but WITHOUT8* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or9* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License10* version 2 for more details (a copy is included in the LICENSE file that11* accompanied this code).12*13* You should have received a copy of the GNU General Public License version14* 2 along with this work; if not, write to the Free Software Foundation,15* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.16*17* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA18* or visit www.oracle.com if you need additional information or have any19* questions.20*/2122/*23* This file is available under and governed by the GNU General Public24* License version 2 only, as published by the Free Software Foundation.25* However, the following notice accompanied the original version of this26* file:27*28* Written by Doug Lea with assistance from members of JCP JSR-16629* Expert Group and released to the public domain, as explained at30* http://creativecommons.org/publicdomain/zero/1.0/31*/3233/*34* @test35* @bug 4949279 693785736* @summary Independent instantiations of Random() have distinct seeds.37* @key randomness38*/3940import java.util.ArrayList;41import java.util.HashSet;42import java.util.List;43import java.util.Random;4445public class DistinctSeeds {46public static void main(String[] args) throws Exception {47// Strictly speaking, it is possible for these to randomly fail,48// but the probability should be small (approximately 2**-48).49if (new Random().nextLong() == new Random().nextLong() ||50new Random().nextLong() == new Random().nextLong())51throw new RuntimeException("Random() seeds not unique.");5253// Now try generating seeds concurrently54class RandomCollector implements Runnable {55long[] randoms = new long[1<<17];56public void run() {57for (int i = 0; i < randoms.length; i++)58randoms[i] = new Random().nextLong();59}60}61final int threadCount = 2;62List<RandomCollector> collectors = new ArrayList<>();63List<Thread> threads = new ArrayList<>();64for (int i = 0; i < threadCount; i++) {65RandomCollector r = new RandomCollector();66collectors.add(r);67threads.add(new Thread(r));68}69for (Thread thread : threads)70thread.start();71for (Thread thread : threads)72thread.join();73int collisions = 0;74HashSet<Long> s = new HashSet<>();75for (RandomCollector r : collectors) {76for (long x : r.randoms) {77if (s.contains(x))78collisions++;79s.add(x);80}81}82System.out.printf("collisions=%d%n", collisions);83if (collisions > 10)84throw new Error("too many collisions");85}86}878889