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

Discussion

Sample30 is run - what will be the output?

import java.util.concurrent.atomic.AtomicInteger;

public class Sample30
{
    static AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable r = () -> { for (int i = 0; i < 10000; i++) count.incrementAndGet(); };
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println(count.get());
    }
}

  • A.A compile error
  • B.20000
  • C.Some value from 10000 to 20000
  • D.10000

Answer: B

incrementAndGet performs the read, add and write as one indivisible operation, so no update can be lost however the two threads interleave. With both joins completed before the print, the total is exactly 20000. This is the fix for the plain and the volatile counter alike.

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

Post your comment

Please log in or register to post a comment.