1

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();
    }
}
Anne Maier
  • 299
  • 1
  • 8
  • 1
    Yeah, still thread-safe. No need to synchronize this `randomSum` method since you haven't modify any value outside the method. – Sachith Dickwella Jun 09 '21 at 06:27
  • 3
    @Sachith Dickwella Well - actually `random.nextInt` modifies random internally, but Random is thread safe. – rghome Jun 09 '21 at 06:33
  • 1
    This is not exactly a duplicate of https://stackoverflow.com/questions/5819638, but if `Random` is thread-safe, then it follows that your `randomSum` method is thread-safe, since `sum` and `i` are local variables and therefore thread-confined. – Stephen C Jun 09 '21 at 06:43

1 Answers1

6

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
rghome
  • 8,529
  • 8
  • 43
  • 62