Thread safety if loop is thread safe

141 Views Asked by At

The while loop in this question is thread safe: AtomicInteger thread safety. If I insert the randomSum method in the thread safe while loop, is the code still thread safe? Or should the randomSum method be synchronized?

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class Print implements Runnable {
    static AtomicInteger atomicInteger = new AtomicInteger(0);
    static Random random = new Random(1);

    public static int randomSum() {
        int sum = 0;
        for (int i = 0; i < 10; i++) {
            sum += random.nextInt();
        }
        return sum;
    }

    @Override
    public void run() {
        while (atomicInteger.getAndIncrement() < 100)
            System.out.println(randomSum() + " " + Thread.currentThread());
    }

    public static void main(String[] args) throws InterruptedException {
        ArrayList<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++)
            threads.add(new Thread(new Print()));

        for (Thread thread : threads)
            thread.start();

        for (Thread thread : threads)
            thread.join();
    }
}
1

There are 1 best solutions below

0
On

The method randomSum is thread-safe, as is its use.

The only shared object is random. The Java API documentation states that instances of java.util.Random are thread-safe but may encounter performance issues if used concurrently (presumably due to synchronization) and that ThreadLocalRandom should be considered instead if performance is an issue.