001/* 002 * Copyright 2014-2019 Ping Identity Corporation 003 * All Rights Reserved. 004 */ 005/* 006 * Copyright (C) 2014-2019 Ping Identity Corporation 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 = new ThreadLocal<>(); 048 049 050 051 /** 052 * Prevents this class from being instantiated. 053 */ 054 private ThreadLocalRandom() 055 { 056 // No implementation required. 057 } 058 059 060 061 /** 062 * Gets a thread-local random number generator instance. 063 * 064 * @return A thread-local random number generator instance. 065 */ 066 public static Random get() 067 { 068 Random r = INSTANCES.get(); 069 if (r == null) 070 { 071 final long seed; 072 synchronized (SEED_RANDOM) 073 { 074 seed = SEED_RANDOM.nextLong(); 075 } 076 077 r = new Random(seed); 078 INSTANCES.set(r); 079 } 080 081 return r; 082 } 083}