title: Java Concurrency in Practice "Listing 7.1. Using a volatile field to hold cancellation state.". synchronized for visibility?
body: <p>I am reading Java Concurrency in Practice and encounter the following code snippets. I think the usage of <code>synchronized</code> is for visibility (let the thread calling <code>generator.get()</code> see the latest <code>primes</code>), because the task <code>PrimeGenerator</code> is executed by one single thread and the internal <code>primes</code> is not shared with other threads.</p>
  
  <p>Am I right?</p>
  
  <blockquote>
    <p>Listing 7.1. Using a volatile field to hold cancellation state.</p>
  </blockquote>
  
  <pre><code>@ThreadSafe
  public class PrimeGenerator implements Runnable {
      @GuardedBy("this")
      private final List&lt;BigInteger&gt; primes
              = new ArrayList&lt;BigInteger&gt;();
      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&lt;BigInteger&gt; get() {
          return new ArrayList&lt;BigInteger&gt;(primes);
      }
  }
  </code></pre>
  
  <blockquote>
    <p>Listing 7.2. Generating a second’s worth of prime numbers.</p>
  </blockquote>
  
  <pre><code>List&lt;BigInteger&gt; aSecondOfPrimes() throws InterruptedException {
      PrimeGenerator generator = new PrimeGenerator();
      new Thread(generator).start();
      try {
          SECONDS.sleep(1);
      } finally {
          generator.cancel();
      }
      return generator.get();
  }
  </code></pre>