001/* 002 * Copyright 2014-2017 UnboundID Corp. 003 * All Rights Reserved. 004 */ 005/* 006 * Copyright (C) 2014-2017 UnboundID Corp. 007 * 008 * This program is free software; you can redistribute it and/or modify 009 * it under the terms of the GNU General Public License (GPLv2 only) 010 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) 011 * as published by the Free Software Foundation. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Public License for more details. 017 * 018 * You should have received a copy of the GNU General Public License 019 * along with this program; if not, see <http://www.gnu.org/licenses>. 020 */ 021package com.unboundid.util; 022 023 024 025import java.util.Random; 026 027 028 029/** 030 * This class provides a means of obtaining a thread-local random number 031 * generator that can be used by the current thread without the need for 032 * synchronization. 033 */ 034@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE) 035public final class ThreadLocalRandom 036{ 037 /** 038 * The random number generator that will be used to seed per-thread instances. 039 */ 040 private static final Random SEED_RANDOM = new Random(); 041 042 043 044 /** 045 * The thread-local instances that have been created. 046 */ 047 private static final ThreadLocal<Random> INSTANCES = 048 new ThreadLocal<Random>(); 049 050 051 052 /** 053 * Prevents this class from being instantiated. 054 */ 055 private ThreadLocalRandom() 056 { 057 // No implementation required. 058 } 059 060 061 062 /** 063 * Gets a thread-local random number generator instance. 064 * 065 * @return A thread-local random number generator instance. 066 */ 067 public static Random get() 068 { 069 Random r = INSTANCES.get(); 070 if (r == null) 071 { 072 final long seed; 073 synchronized (SEED_RANDOM) 074 { 075 seed = SEED_RANDOM.nextLong(); 076 } 077 078 r = new Random(seed); 079 INSTANCES.set(r); 080 } 081 082 return r; 083 } 084}