1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 package org.apache.giraph.writable.kryo; 19 20 import java.util.Random; 21 22 /** 23 * Transient Random class. Seed/state is not kept after 24 * serializing/deserializing. 25 * 26 * Within Blocks Framework - if we initialize Random within the Piece, when 27 * it's serialzied and copied to all workers and all threads - keeping seed 28 * would cause same series of random numbers to be generated everywhere. 29 * 30 * So this class is safe to be used in Pieces, while using regular Random 31 * class is forbidden to be serialized. 32 * Best approach would be to not have Random serialized, and create it on 33 * workers, where possible. 34 */ 35 public class TransientRandom { 36 /** Instance of random object */ 37 private final transient Random random = new Random(); 38 39 /** 40 * Get instance of Random 41 * @return Random instance 42 */ 43 public Random get() { 44 return random; 45 } 46 47 /** 48 * Returns a pseudorandom, uniformly distributed {@code int} value 49 * between 0 (inclusive) and the specified value (exclusive), drawn from 50 * this random number generator's sequence. 51 * 52 * @param n Given upper limit 53 * @return pseudorandom integer number in [0, n) range. 54 */ 55 public int nextInt(int n) { 56 return random.nextInt(n); 57 } 58 59 /** 60 * Returns the next pseudorandom, uniformly distributed 61 * {@code double} value between {@code 0.0} and 62 * {@code 1.0} from this random number generator's sequence. 63 * 64 * @return pseudorandom number in [0, 1) 65 */ 66 public double nextDouble() { 67 return random.nextDouble(); 68 } 69 }