2

I am reading Java Concurrency in Practice and encounter the following code snippets. I think the usage of synchronized is for visibility (let the thread calling generator.get() see the latest primes), because the task PrimeGenerator is executed by one single thread and the internal primes is not shared with other threads.

Am I right?

Listing 7.1. Using a volatile field to hold cancellation state.

@ThreadSafe
public class PrimeGenerator implements Runnable {
    @GuardedBy("this")
    private final List<BigInteger> primes
            = new ArrayList<BigInteger>();
    private volatile boolean cancelled;

    public void run() {
        BigInteger p = BigInteger.ONE;
        while (!cancelled) {
            p = p.nextProbablePrime();
            synchronized (this) {
                primes.add(p);
            }
        }
    }

    public void cancel() {
        cancelled = true;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<BigInteger>(primes);
    }
}

Listing 7.2. Generating a second’s worth of prime numbers.

List<BigInteger> aSecondOfPrimes() throws InterruptedException {
    PrimeGenerator generator = new PrimeGenerator();
    new Thread(generator).start();
    try {
        SECONDS.sleep(1);
    } finally {
        generator.cancel();
    }
    return generator.get();
}
Jason Law
  • 965
  • 1
  • 9
  • 21
  • Apparently so. Is there anything else that's unclear about it? I don't think SO allows us to give an answer of "Yes." – RealSkeptic Dec 31 '19 at 10:02
  • @RealSkeptic No, just want to make sure my understanding is right. Sorry for asking such a question. – Jason Law Dec 31 '19 at 10:05

1 Answers1

1

I think the usage of synchronized has two purposes.

  1. Visibility. Let the reading thread see the latest primes changed by adding threading.
  2. Atomicity. When the reading thread is reading, the adding thread is blocked, and vice versa.
Jason Law
  • 965
  • 1
  • 9
  • 21
  • See also this answer: https://stackoverflow.com/a/34261294/12284870 Also, section 3.1.1 ("Stale Data") of this book (i.e. Java Concurrency in Practice) affirms this as a way to ensure visibility. – Yonas Sep 09 '21 at 19:24