1 /* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.util.Random; 25 import java.util.SplittableRandom; 26 27 public class RandomSeed { 28 private long seed = 0L; 29 private Random rnd = null; 30 private SplittableRandom srnd = null; 31 32 public RandomSeed(boolean isSplittableRandom) { 33 init(isSplittableRandom); 34 } 35 36 private void init(boolean isSplittableRandom) { 37 // obtain seed from environment if supplied 38 boolean isSeedProvided = false; 39 try { 40 // note that Long.valueOf(null) also throws a NumberFormatException 41 // so if the property is undefined this will still work correctly 42 seed = Long.valueOf(System.getProperty("seed")); 43 isSeedProvided = true; 44 } catch (NumberFormatException e) { 45 // do nothing: isSeedProvided is already false 46 } 47 48 // if no seed from environment, create a fresh one 49 Random tmpRnd = null; 50 if (!isSeedProvided) { 51 tmpRnd = new Random(); 52 seed = tmpRnd.nextLong(); 53 } 54 55 // create the PRNG 56 if (isSplittableRandom) { 57 srnd = new SplittableRandom(seed); 58 } else { 59 rnd = tmpRnd != null ? tmpRnd : new Random(); 60 rnd.setSeed(seed); 61 } 62 } 63 64 public Random getRandom() { 65 if (rnd == null) { 66 throw new IllegalStateException("Variable of type Random not initialized"); 67 } 68 return rnd; 69 } 70 71 public SplittableRandom getSplittableRandom() { 72 if (srnd == null) { 73 throw new IllegalStateException("Variable of type SplittableRandom not initialized"); 74 } 75 return srnd; 76 } 77 78 public long getSeed() { 79 return seed; 80 } 81 }