java.util.concurrent.atomic package has classes which support atomic operation. With atomic classes we on longer need the lock or synchronization.
AtomicInteger and AtomicLong are two atomic classes.
get( ), set( ), compareAndSet( ), decrementAndGet( ), and getAndSet( ) from them perform the atomic actions.
import java.util.concurrent.atomic.AtomicLong;
class ID {
private static AtomicLong nextID = new AtomicLong(0);
static long getNextID() {
return nextID.getAndIncrement();
}
}
The following code demonstrates an AtomicInteger in a thread. It returns unique IDs in a thread-safe manner via AtomicLong.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static AtomicInteger ai = new AtomicInteger(0);
public static void main(String args[]) {
new AtomThread("A");
new AtomThread("B");
}
}
class AtomThread implements Runnable {
String name;
AtomThread(String n) {
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
for (int i = 1; i <= 3; i++)
System.out.println(name + " got: " + Main.ai.getAndSet(i));
}
}