1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package io.netty.util.internal;
24
25 import io.netty.util.internal.logging.InternalLogger;
26 import io.netty.util.internal.logging.InternalLoggerFactory;
27
28 import java.lang.Thread.UncaughtExceptionHandler;
29 import java.security.SecureRandom;
30 import java.util.Random;
31 import java.util.concurrent.BlockingQueue;
32 import java.util.concurrent.LinkedBlockingQueue;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.atomic.AtomicLong;
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 @SuppressWarnings("all")
61 public final class ThreadLocalRandom extends Random {
62
63 private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadLocalRandom.class);
64
65 private static final AtomicLong seedUniquifier = new AtomicLong();
66
67 private static volatile long initialSeedUniquifier;
68
69 public static void setInitialSeedUniquifier(long initialSeedUniquifier) {
70 ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier;
71 }
72
73 public static synchronized long getInitialSeedUniquifier() {
74
75 long initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier;
76 if (initialSeedUniquifier == 0) {
77
78 ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier =
79 SystemPropertyUtil.getLong("io.netty.initialSeedUniquifier", 0);
80 }
81
82
83 if (initialSeedUniquifier == 0) {
84 boolean secureRandom = SystemPropertyUtil.getBoolean("java.util.secureRandomSeed", false);
85 if (secureRandom) {
86
87
88 final BlockingQueue<Long> queue = new LinkedBlockingQueue<Long>();
89 Thread generatorThread = new Thread("initialSeedUniquifierGenerator") {
90 @Override
91 public void run() {
92 SecureRandom random = new SecureRandom();
93 final byte[] seed = random.generateSeed(8);
94 long s = ((long) seed[0] & 0xff) << 56 |
95 ((long) seed[1] & 0xff) << 48 |
96 ((long) seed[2] & 0xff) << 40 |
97 ((long) seed[3] & 0xff) << 32 |
98 ((long) seed[4] & 0xff) << 24 |
99 ((long) seed[5] & 0xff) << 16 |
100 ((long) seed[6] & 0xff) << 8 |
101 (long) seed[7] & 0xff;
102 queue.add(s);
103 }
104 };
105 generatorThread.setDaemon(true);
106 generatorThread.start();
107 generatorThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
108 @Override
109 public void uncaughtException(Thread t, Throwable e) {
110 logger.debug("An exception has been raised by {}", t.getName(), e);
111 }
112 });
113
114
115 final long timeoutSeconds = 3;
116 final long deadLine = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
117 boolean interrupted = false;
118 for (;;) {
119 long waitTime = deadLine - System.nanoTime();
120 if (waitTime <= 0) {
121 generatorThread.interrupt();
122 logger.warn(
123 "Failed to generate a seed from SecureRandom within {} seconds. " +
124 "Not enough entrophy?", timeoutSeconds
125 );
126 break;
127 }
128
129 try {
130 Long seed = queue.poll(waitTime, TimeUnit.NANOSECONDS);
131 if (seed != null) {
132 initialSeedUniquifier = seed;
133 break;
134 }
135 } catch (InterruptedException e) {
136 interrupted = true;
137 logger.warn("Failed to generate a seed from SecureRandom due to an InterruptedException.");
138 break;
139 }
140 }
141
142
143 initialSeedUniquifier ^= 0x3255ecdc33bae119L;
144 initialSeedUniquifier ^= Long.reverse(System.nanoTime());
145
146 if (interrupted) {
147
148 Thread.currentThread().interrupt();
149
150
151
152 generatorThread.interrupt();
153 }
154 } else {
155 initialSeedUniquifier = mix64(System.currentTimeMillis()) ^ mix64(System.nanoTime());
156 }
157 ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier;
158 }
159
160 return initialSeedUniquifier;
161 }
162
163 private static long newSeed() {
164 final long startTime = System.nanoTime();
165 for (;;) {
166 final long current = seedUniquifier.get();
167 final long actualCurrent = current != 0? current : getInitialSeedUniquifier();
168
169
170 final long next = actualCurrent * 181783497276652981L;
171
172 if (seedUniquifier.compareAndSet(current, next)) {
173 if (current == 0 && logger.isDebugEnabled()) {
174 logger.debug(String.format(
175 "-Dio.netty.initialSeedUniquifier: 0x%016x (took %d ms)",
176 actualCurrent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)));
177 }
178 return next ^ System.nanoTime();
179 }
180 }
181 }
182
183
184
185 private static long mix64(long z) {
186 z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
187 z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
188 return z ^ (z >>> 33);
189 }
190
191
192 private static final long multiplier = 0x5DEECE66DL;
193 private static final long addend = 0xBL;
194 private static final long mask = (1L << 48) - 1;
195
196
197
198
199 private long rnd;
200
201
202
203
204
205
206
207 boolean initialized;
208
209
210
211
212 private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
213
214
215
216
217 ThreadLocalRandom() {
218 super(newSeed());
219 initialized = true;
220 }
221
222
223
224
225
226
227 public static ThreadLocalRandom current() {
228 return InternalThreadLocalMap.get().random();
229 }
230
231
232
233
234
235
236
237 public void setSeed(long seed) {
238 if (initialized) {
239 throw new UnsupportedOperationException();
240 }
241 rnd = (seed ^ multiplier) & mask;
242 }
243
244 protected int next(int bits) {
245 rnd = (rnd * multiplier + addend) & mask;
246 return (int) (rnd >>> (48 - bits));
247 }
248
249
250
251
252
253
254
255
256
257
258
259 public int nextInt(int least, int bound) {
260 if (least >= bound) {
261 throw new IllegalArgumentException();
262 }
263 return nextInt(bound - least) + least;
264 }
265
266
267
268
269
270
271
272
273
274
275 public long nextLong(long n) {
276 if (n <= 0) {
277 throw new IllegalArgumentException("n must be positive");
278 }
279
280
281
282
283
284
285 long offset = 0;
286 while (n >= Integer.MAX_VALUE) {
287 int bits = next(2);
288 long half = n >>> 1;
289 long nextn = ((bits & 2) == 0) ? half : n - half;
290 if ((bits & 1) == 0) {
291 offset += n - nextn;
292 }
293 n = nextn;
294 }
295 return offset + nextInt((int) n);
296 }
297
298
299
300
301
302
303
304
305
306
307
308 public long nextLong(long least, long bound) {
309 if (least >= bound) {
310 throw new IllegalArgumentException();
311 }
312 return nextLong(bound - least) + least;
313 }
314
315
316
317
318
319
320
321
322
323
324 public double nextDouble(double n) {
325 if (n <= 0) {
326 throw new IllegalArgumentException("n must be positive");
327 }
328 return nextDouble() * n;
329 }
330
331
332
333
334
335
336
337
338
339
340
341 public double nextDouble(double least, double bound) {
342 if (least >= bound) {
343 throw new IllegalArgumentException();
344 }
345 return nextDouble() * (bound - least) + least;
346 }
347
348 private static final long serialVersionUID = -5851777807851030925L;
349 }