001/*
002 * Copyright 2014-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2014-2024 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2014-2024 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.util;
037
038
039
040import java.util.Random;
041
042
043
044/**
045 * This class provides a means of obtaining a thread-local random number
046 * generator that can be used by the current thread without the need for
047 * synchronization.
048 */
049@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
050public final class ThreadLocalRandom
051{
052  /**
053   * The random number generator that will be used to seed per-thread instances.
054   */
055  @NotNull private static final Random SEED_RANDOM = new Random();
056
057
058
059  /**
060   * The thread-local instances that have been created.
061   */
062  @NotNull private static final ThreadLocal<Random> INSTANCES =
063       new ThreadLocal<>();
064
065
066
067  /**
068   * Prevents this class from being instantiated.
069   */
070  private ThreadLocalRandom()
071  {
072    // No implementation required.
073  }
074
075
076
077  /**
078   * Gets a thread-local random number generator instance.
079   *
080   * @return  A thread-local random number generator instance.
081   */
082  @NotNull()
083  public static Random get()
084  {
085    Random r = INSTANCES.get();
086    if (r == null)
087    {
088      final long seed;
089      synchronized (SEED_RANDOM)
090      {
091        seed = SEED_RANDOM.nextLong();
092      }
093
094      r = new Random(seed);
095      INSTANCES.set(r);
096    }
097
098    return r;
099  }
100}