Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample20 is run - what will be the output?

public class Sample20
{
    static volatile long total = 0;

    static class Adder extends Thread
    {
        public void run()
        {
            for (int i = 0; i < 50000; i++) total++;
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Adder x = new Adder(), y = new Adder();
        x.start(); y.start();
        x.join(); y.join();
        System.out.println(total);
    }
}

  • A.Exactly 100000, because volatile makes each increment atomic
  • B.Exactly 100000, because volatile forces the threads to run in turn
  • C.Exactly 50000, because volatile means only one write survives
  • D.Some value from 50000 to 100000; volatile does not make the increment atomic

Answer: D

volatile makes each read and each write atomic and visible, which is not enough: the increment is three operations and another thread can act between them, so updates are still lost. Declaring the field long does not help either; volatile only guarantees that a wide value is never seen half-written. This is the single most common misuse of the keyword.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.