[concurrency-interest] syntax sugar for lazy instantiation

Joe Bowbeer joe.bowbeer at gmail.com
Tue Jun 23 20:18:53 EDT 2009


Nit: I think it's misleading to implement Callable in this case.  That
forces LazyField to have a public call() method, but it's only supposed to
be called internally.

Instead, I suggest an abstract protected method with a descriptive name such
as "create" or "construct" or "initialize".

private final LazyField<Logger> antLogger = new LazyField<Logger>() {
protected Logger create() {
return Logger.getLogger(Log4jListener.LOG_ANT);
}
};

Another template for this (other than ThreadLocal) is SwingWorker, in which
users override the doInBackground method, while the SwingWorker itself
implements Future using a private FutureTask instance.

Joe

On Tue, Jun 23, 2009 at 2:03 PM, Ashley Williams wrote:

> Included this so now we have:
> @ThreadSafe
> public abstract class LazyField<T> implements Callable<T> {
> private volatile T obj;
>
> public T get() {
> // use a local variable to save on multiple reads of a volatile
> T result = obj;
> if (result == null) {
> synchronized (this) {
> if (result == null) {
> result = call();
> obj = result;
> }
> }
> }
> return result;
> }
> }
>
> with usage example:
>
> private final LazyField<Logger> antLogger = new LazyField<Logger>() {
> public Logger call() throws Exception {
> return Logger.getLogger(Log4jListener.LOG_ANT);
> }
> };
>
> Looking a lot tidier now.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20090623/1bcb3a91/attachment.html>


More information about the Concurrency-interest mailing list