Re: SingletonHolder reinvented.
Just simplified version:
public class SingletonHolder<T> implements Callable<T> {
private AtomicReference<T> _instance = new AtomicReference<T>();
private AtomicReference<FutureTask<T>> _future = new
AtomicReference<FutureTask<T>>();
public T get() {
try {
T result = _instance.get();
if (result != null) {
return result; // Return value if it has already been initialized.
}
if (_future.compareAndSet(null, new FutureTask<T>(this))) { //
create and try to set to _future
_future.get().run(); // run the task if previous operation
succeed, executed only once!
}
result = _future.get().get(); // get result of execution..
if (result == null) {
throw new IllegalStateException(...); // It must not be null
}
_instance.compareAndSet(null, result); // set only if it was not
set already
return result;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(...);
} catch (ExecutionException e) {
throw new RuntimeException(...);
}
}
// This method is to be overridden by subclasses.
public T call() throws Exception {
throw new IllegalStateException("call is not implemented");
}
}