Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created May 28, 2012 03:48
Show Gist options
  • Save hpcx82/2817124 to your computer and use it in GitHub Desktop.
Save hpcx82/2817124 to your computer and use it in GitHub Desktop.
A generic lazy reference class
import java.util.concurrent.atomic.AtomicReference;
public class LazyReference{
abstract static class LazyRef<T> {
// BUG1: should be final
// member start with _
private final AtomicReference<T> _ref = new AtomicReference<T>();
public LazyRef()
{
System.out.println("LazyRef<T>::LazyRef");
}
public T get() {
T t = _ref.get();
if (t == null) {
t = generate();
_ref.compareAndSet(null, t); // the reason we use compareAndSet here is because there is a race condition that multiple thread may "generate" a instance, but we just make sure the first generated one as the stored one.
}
return t;
}
// BUG2: need to provide a clear method so the LazyRef could be re-generated.
public void clear()
{
_ref.set(null);
}
abstract T generate();
}
// testing class
static class TestObject {
public TestObject()
{
System.out.println("TestObject::TestObject");
}
public void print() {
System.out.println("TestObject::print");
}
}
public static void main(String[] args) {
LazyRef<TestObject> lzObject = new LazyRef<TestObject>() {
TestObject generate() {
return new TestObject();
}
};
lzObject.get().print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment