Code example for AtomicReference

Methods: compareAndSet, set

0
	private enum State { 
		NEW, INITIALIZING, INITIALIZED
	}; 
 
	private final AtomicReference<State> init = new AtomicReference<State>(
			State.NEW);
 
	public AbstractFoo(int x, int y) {
		initialize(x, y);
	} 
 
	// This constructor and the following method allow 
	// subclass's readObject method to initialize our state. 
	protected AbstractFoo() { 
	} 
 
	protected final void initialize(int x, int y) {
		if (!init.compareAndSet(State.NEW, State.INITIALIZING))
			throw new IllegalStateException("Already initialized");
		this.x = x;
		this.y = y;
		// Do anything else the original constructor did 
		init.set(State.INITIALIZED);
	} 
 
	// These methods provide access to internal state so it can 
	// be manually serialized by subclass's writeObject method. 
	protected final int getX() {