Created
May 28, 2012 03:48
-
-
Save hpcx82/2817124 to your computer and use it in GitHub Desktop.
A generic lazy reference class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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