Consider the following program and choose the correct option that describes its output:
import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String []args) { AtomicInteger i = new AtomicInteger(0); increment(i);/*from w w w . j a v a 2s .c o m*/ System.out.println(i); } static void increment(AtomicInteger atomicInt){ atomicInt.incrementAndGet(); } }
a)0 b)1 c)this program throws an UnsafeIncrementException d)this program throws a NonThreadContextException
b)
the call atomicInt
.incrementAndGet()
; mutates the integer value passed through the reference variable atomicInt
, so the changed value is printed in the main()
method.
Note that AtomicInteger can be used in thread or non- thread context though it is not of any practical use when used in single-threaded programs.