Inspectopedia Help

'ThreadLocalRandom' instance might be shared

Reports java.util.concurrent.ThreadLocalRandom instances which might be shared between threads.

A ThreadLocalRandom 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.

Usages of ThreadLocalRandom should typically look like ThreadLocalRandom.current().nextInt(...) (or nextDouble(...) etc.). When all usages are in this form, ThreadLocalRandom instances cannot be used accidentally by multiple threads.

Example:

class Main { void printRandomNumbersAsync() { ThreadLocalRandom random = ThreadLocalRandom.current(); CompletableFuture.supplyAsync(() -> generateNumbers(random)) .thenAccept(numbers -> System.out.println(Arrays.toString(numbers))); } private int[] generateNumbers(Random random) { return random.ints(1000, 0, 100).toArray(); } }

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

SharedThreadLocalRandom
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Threading issues

Use the options to list methods that are safe to be passed to ThreadLocalRandom instances as an argument. It's possible to use regular expressions for method names.

Inspection options

Here you can find the description of settings available for the 'ThreadLocalRandom' instance might be shared inspection, and the reference of their default values.

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.2, Qodana for JVM 2024.2,

Can be installed with plugin:

Java, 242.22892

Last modified: 11 September 2024