Support Online
Skip to main content

Random Number Generation Methods in Java: Safe and Multi-Threaded Random Guide

🚀 What Will You Learn in This Guide?

In this guide, you will learn the different methods used for random number generation in Java.
By examining the classes Random, Math.random(), ThreadLocalRandom and SecureRandom
You will discover how to provide safe, performant and controlled randomness in different scenarios.

🧠 Technical Summary

Main Topic: Random number generation in Java.
Problem it solves: The need to generate random data in situations such as games, tests, simulations or encryption.
User Steps:

  1. Selecting the randomness class (Random, ThreadLocalRandom, SecureRandom)
  2. Define specific range if necessary
  3. Generating numbers in different data types (int, double, byte, etc.)
  4. Working safely in multi-threading

🎯 Java Random Number Generation Methods

1️⃣ java.util.Random – Standard Random Generator

import java.util.Random;
Random rastgele = new Random();
int sayi = rastgele.nextInt();
System.out.println(sayi);

🧠 With this method you generate a random integer (int).

🔹 Seed Value Usage


Random sabitRastgele = new Random(12345);
int tekrarliSayi = sabitRastgele.nextInt();

🧠 When run with the same seed, the same results are produced (provides repeatability).


2️⃣ Generating Random Numbers in a Specific Range


Random rastgele = new Random();
int zar = rastgele.nextInt(6) + 1; // 1-6 arası sayı
System.out.println(zar);

🧠 nextInt(x) produces numbers in the range 0–(x−1), so +1 is added.

Simpler with ThreadLocalRandom:


int sayi = ThreadLocalRandom.current().nextInt(1, 11);
System.out.println(sayi);

🧠 It is the most efficient method that can be used in multi-threading.


3️⃣ Decimal (Double/Float) and Other Types


Random r = new Random();
double d = r.nextDouble(); // 0.0 – 1.0 arası
float f = r.nextFloat(); // 0.0f – 1.0f arası
long l = r.nextLong(); // Rastgele long değer
boolean b = r.nextBoolean();// true veya false

🧠 Random class provides special methods for different data types.

Random Byte Sequence


byte[] dizi = new byte[5];
r.nextBytes(dizi);
System.out.println(Arrays.toString(dizi));

🧠 It is used to generate random data in testing or encryption processes.


🧵 4️⃣ Multithreading Environment: ThreadLocalRandom

ThreadLocalRandom creates a separate random generator for each thread. Thus, locking and contention problems are eliminated.


package ornek.com.random;

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomOrnek {
public static void main(String[] args) {
Runnable r = () -> {
String isim = Thread.currentThread().getName();
int sayi = ThreadLocalRandom.current().nextInt();
System.out.println(isim + " -> " + sayi);
};

for (int i = 0; i < 3; i++) {
new Thread(r, "IsParcacigi-" + i).start();
}
}
}

📤 Sample Output:


IsParcacigi-0 -> 2145234
IsParcacigi-1 -> -10324567
IsParcacigi-2 -> 8793245

🧠 The seed value cannot be changed in ThreadLocalRandom (throws UnsupportedOperationException).


🔒 5️⃣ Secure Randomness: java.security.SecureRandom

Provides cryptographically secure random number generation. Ideal for generating API keys, tokens or passwords.


import java.security.SecureRandom;

SecureRandom guvenli = new SecureRandom();
int guvenliSayi = guvenli.nextInt();
System.out.println(guvenliSayi);

🧠 SecureRandom uses the operating system's entropy resources and is more secure, but slower.


💬 Frequently Asked Questions (FAQ)

  1. What is the difference between Math.random() and Random?

Math.random() just returns double and is based on the Random class. Random, on the other hand, can produce different data types.

  1. Is the Random class thread-safe?

No. ThreadLocalRandom should be preferred in multi-threading.

  1. Why is SecureRandom slow?

It provides extra security because it collects data from the system's entropy pool, but this also extends the processing time.

  1. What does nextInt(10) return?

Generates integers between 0 (inclusive) and 9 (excluded).

  1. Are random numbers truly random?

No, these are pseudo-random numbers. The same seed gives the same result.


🏁 Conclusion

Java offers different randomization tools based on performance, multi-threading support and security requirements:

🧩 Class💡 Usage Area
RandomIt is used for simple random operations.
ThreadLocalRandomProvides performant randomness in multithreaded environments.
SecureRandomIt is used in critical operations such as security, encryption and token generation.
💡 Tip: Choose ThreadLocalRandom in performance-oriented projects and SecureRandom in security-oriented systems.

☁️ You can experience safe and fast random data generation by testing all these methods in your Java applications on GenixNode!