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()}.
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<UniformRandomProvider> rng =
52 * new ThreadLocal<UniformRandomProvider>() {
53 * @Override
54 * protected UniformRandomProvider initialValue() {
55 * return RandomSource.TWO_CMRES_SELECT.create(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 final EnumMap<RandomSource, ThreadLocal<UniformRandomProvider>> SOURCES =
73 new EnumMap<>(RandomSource.class);
74
75 /** No public construction. */
76 private ThreadLocalRandomSource() {}
77
78 /**
79 * Extend the {@link ThreadLocal} to allow creation of the desired {@link RandomSource}.
80 */
81 private static class ThreadLocalRng extends ThreadLocal<UniformRandomProvider> {
82 /** The source. */
83 private final RandomSource source;
84
85 /**
86 * Create a new instance.
87 *
88 * @param source the source
89 */
90 ThreadLocalRng(RandomSource source) {
91 this.source = source;
92 }
93
94 @Override
95 protected UniformRandomProvider initialValue() {
96 // Create with the default seed generation method
97 return source.create();
98 }
99 }
100
101 /**
102 * Returns the current thread's copy of the given {@code source}. If there is no
103 * value for the current thread, it is first initialized to the value returned
104 * by {@link RandomSource#create()}.
105 *
106 * <p>Note if the {@code source} requires additional arguments then it is not
107 * supported.
108 *
109 * @param source the source
110 * @return the current thread's value of the {@code source}.
111 * @throws IllegalArgumentException if the source is null or the source requires arguments
112 */
113 public static UniformRandomProvider current(RandomSource source) {
114 ThreadLocal<UniformRandomProvider> rng = SOURCES.get(source);
115 // Implement double-checked locking:
116 // https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
117 if (rng == null) {
118 // Do the checks on the source here since it is an edge case
119 // and the EnumMap handles null (returning null).
120 if (source == null) {
121 throw new IllegalArgumentException("Random source is null");
122 }
123
124 synchronized (SOURCES) {
125 rng = SOURCES.computeIfAbsent(source, ThreadLocalRng::new);
126 }
127 }
128 return rng.get();
129 }
130 }