How do the Java atomic classes avoid locks, and what operations do they support?
The atomic classes do not take a lock at all. They use the processor's own instruction for an atomic compare and swap, which does the whole job in one step that cannot be interrupted by another thread.
So what operations do they support? The class AtomicInteger gives you a set of methods that cover the things you would want a counter to do.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class Main {
public static void main(String[] args) {
AtomicInteger count = new AtomicInteger();
// Reading and writing.
count.set(10);
System.out.println("get : " + count.get());
System.out.println("set : " + count.getAndSet(20));
// Adding and taking away.
System.out.println("increment : " + count.incrementAndGet());
System.out.println("decrement : " + count.decrementAndGet());
System.out.println("add : " + count.addAndGet(5));
System.out.println("getAndAdd : " + count.getAndAdd(5));
// Changing it only if it is what you expect.
System.out.println("compare : " + count.compareAndSet(30, 100));
System.out.println("compare : " + count.compareAndSet(30, 200));
System.out.println("now : " + count.get());
// The same idea for an object rather than a number.
AtomicReference<String> name = new AtomicReference<String>("Ada");
name.set("Grace");
System.out.println("name : " + name.get());
}
}
So the answer to the question is this. They avoid the lock by using a single processor instruction, and they support reading, writing, adding, taking away, and changing the value only when it is what you expected it to be.
There is a family of them. There is AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference for a general object. There are the versions for the primitive types that do not have a class, such as AtomicIntegerArray and AtomicReferenceArray. And there is the class AtomicIntegerFieldUpdater for a field of an object that you cannot change to be final.
The next question in this topic looks at how to use them properly.