Assuming the following class is concurrently accessed by numerous threads, which statement about the Main class is correct?
package mypkg; /*from ww w.ja v a2 s. c o m*/ import java.util.concurrent.atomic.*; public class Main { private static AtomicInteger counter = new AtomicInteger(); private Object lock = new Object(); public synchronized int increment1() { return counter.incrementAndGet(); } public static synchronized int increment2() { return counter.getAndIncrement(); } public int increment3() { synchronized(lock) { return counter.getAndIncrement(); } } }
D.
The code compiles, making Option E incorrect.
The key here is that the AtomicInteger variable is thread-safe regardless of the synchronization methods used to access it.
Therefore, synchronizing on an instance object, as in increment1() or increment3(), or on the class object, as in increment2(), is unnecessary because the AtomicInteger class is already thread-safe.
Option D is the correct answer.