Does this implementation work for Java without secure wireless wireless balance in Java?

advertisements

This is what I have so far, am I going in the right direction? Aim is to use this in scenarios where one thread requires access to the singleton more frequently than other threads, hence lock-less code is desirable, I wanted to use atomic variables for practice.

public final class ThreadSafeLazyCompareAndSwapSingleton {

private ThreadSafeLazyCompareAndSwapSingleton(){}

private static volatile ThreadSafeLazyCompareAndSwapSingleton instance;
private final static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

public static ThreadSafeLazyCompareAndSwapSingleton getCASInstance(){
    if (instance==null){
        boolean obs = instance==null;
        while (!atomicBoolean.compareAndSet(true, obs == (instance==null))){
            instance = new ThreadSafeLazyCompareAndSwapSingleton();
        }
    }
    return instance;
}

}


Uh, it is hard to read with those inline conditions/assigns. It is also pretty much non-standard idiom, so I wonder if you really want to use it.

It has at least the problem that it can create more than one instance (might be acceptable in your case, you cant really avoid that if you want to be lock-free). But I think it also might return more than one instance, which is not what you want to have I guess.

I am not sure if you need a boolean, you could also use a AtomicReferenceFieldUpdater directly on the instance field.

I think the obs is not needed, you would create and return a new instance if you can set the boolean, and loop otherwise:

if (instance!=null)
  return instance;

if (atomicBoolean.compareAndSet(false, true))
{
  instance = new ThreadSafeLazyCompareAndSwapSingleton();
  return instance;
}
while(instance==null);
return instance;

But I really dont think it is a good idea to go with this extra boolean.