View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.rng.simple;
18  
19  import java.util.EnumMap;
20  
21  import org.apache.commons.rng.UniformRandomProvider;
22  
23  /**
24   * This class provides a thread-local {@link UniformRandomProvider}.
25   *
26   * <p>The {@link UniformRandomProvider} is created once-per-thread using the default
27   * construction method {@link RandomSource#create(RandomSource)}.
28   *
29   * <p>Example:</p>
30   * <pre><code>
31   * import org.apache.commons.rng.simple.RandomSource;
32   * import org.apache.commons.rng.simple.ThreadLocalRandomSource;
33   * import org.apache.commons.rng.sampling.distribution.PoissonSampler;
34   *
35   * // Access a thread-safe random number generator
36   * UniformRandomProvider rng = ThreadLocalRandomSource.current(RandomSource.SPLIT_MIX_64);
37   *
38   * // One-time Poisson sample
39   * double mean = 12.3;
40   * int counts = PoissonSampler.of(rng, mean).sample();
41   * </code></pre>
42   *
43   * <p>Note if the {@link RandomSource} requires additional arguments then it is not
44   * supported. The same can be achieved using:</p>
45   *
46   * <pre><code>
47   * import org.apache.commons.rng.simple.RandomSource;
48   * import org.apache.commons.rng.sampling.distribution.PoissonSampler;
49   *
50   * // Provide a thread-safe random number generator with data arguments
51   * private static ThreadLocal&lt;UniformRandomProvider&gt; rng =
52   *     new ThreadLocal&lt;UniformRandomProvider&gt;() {
53   *         &#64;Override
54   *         protected UniformRandomProvider initialValue() {
55   *             return RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 3, 4);
56   *         }
57   *     };
58   *
59   * // One-time Poisson sample using a thread-safe random number generator
60   * double mean = 12.3;
61   * int counts = PoissonSampler.of(rng.get(), mean).sample();
62   * </code></pre>
63   *
64   * @since 1.3
65   */
66  public final class ThreadLocalRandomSource {
67      /**
68       * A map containing the {@link ThreadLocal} instance for each {@link RandomSource}.
69       *
70       * <p>This should only be modified to create new instances in a synchronized block.
71       */
72      private static EnumMap<RandomSource, ThreadLocal<UniformRandomProvider>> sources =
73          new EnumMap<RandomSource,
74                      ThreadLocal<UniformRandomProvider>>(RandomSource.class);
75  
76      /** No public construction. */
77      private ThreadLocalRandomSource() {}
78  
79      /**
80       * Extend the {@link ThreadLocal} to allow creation of the desired {@link RandomSource}.
81       */
82      private static class ThreadLocalRng extends ThreadLocal<UniformRandomProvider> {
83          /** The source. */
84          private final RandomSource source;
85  
86          /**
87           * Create a new instance.
88           *
89           * @param source the source
90           */
91          ThreadLocalRng(RandomSource source) {
92              this.source = source;
93          }
94  
95          @Override
96          protected UniformRandomProvider initialValue() {
97              // Create with the default seed generation method
98              return RandomSource.create(source);
99          }
100     }
101 
102     /**
103      * Returns the current thread's copy of the given {@code source}. If there is no
104      * value for the current thread, it is first initialized to the value returned
105      * by {@link RandomSource#create(RandomSource)}.
106      *
107      * <p>Note if the {@code source} requires additional arguments then it is not
108      * supported.
109      *
110      * @param source the source
111      * @return the current thread's value of the {@code source}.
112      * @throws IllegalArgumentException if the source is null or the source requires arguments
113      */
114     public static UniformRandomProvider current(RandomSource source) {
115         ThreadLocal<UniformRandomProvider> rng = sources.get(source);
116         // Implement double-checked locking:
117         // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
118         if (rng == null) {
119             // Do the checks on the source here since it is an edge case
120             // and the EnumMap handles null (returning null).
121             if (source == null) {
122                 throw new IllegalArgumentException("Random source is null");
123             }
124 
125             synchronized (sources) {
126                 rng = sources.get(source);
127                 if (rng == null) {
128                     rng = new ThreadLocalRng(source);
129                     sources.put(source, rng);
130                 }
131             }
132         }
133         return rng.get();
134     }
135 }