Files
openide/java/java-impl/resources/inspectionDescriptions/SharedThreadLocalRandom.html
Leonid Shalupov 40795fe787 IJI-2422: community/java: move resources under resources root
GitOrigin-RevId: 8b2b63fc6db476ca0c2cfe5cadd84db6c4236d0f
2025-02-05 04:43:28 +00:00

34 lines
1.4 KiB
HTML

<html>
<body>
Reports <code>java.util.concurrent.ThreadLocalRandom</code> instances which might be shared between threads.
<p>
A <code>ThreadLocalRandom</code> should not be shared between threads because that is not thread-safe.
The inspection reports instances that are assigned to a field used as a method argument,
or assigned to a local variable and used in anonymous or nested classes as they might get shared between threads.
</p>
<p>
Usages of <code>ThreadLocalRandom</code> should typically look like <code>ThreadLocalRandom.current().nextInt(...)</code>
(or <code>nextDouble(...)</code> etc.).
When all usages are in this form, <code>ThreadLocalRandom</code> instances cannot be used accidentally by multiple threads.
</p>
<p><b>Example:</b></p>
<pre><code>
class Main {
void printRandomNumbersAsync() {
ThreadLocalRandom random = ThreadLocalRandom.current();
CompletableFuture.supplyAsync(() -&gt; generateNumbers(random))
.thenAccept(numbers -&gt; System.out.println(Arrays.toString(numbers)));
}
private int[] generateNumbers(Random random) {
return random.ints(1000, 0, 100).toArray();
}
}
</code></pre>
<!-- tooltip end -->
<p>
Use the options to list methods that are safe to be passed to <code>ThreadLocalRandom</code> instances as an argument.
It's possible to use regular expressions for method names.
</p>
</body>
</html>