[concurrency-interest] syntax sugar for lazy instantiation

Tim Peierls tim at peierls.net
Tue Jun 23 17:19:31 EDT 2009


Doesn't compile, since call() throws Exception and get() doesn't.

And you need another "result = obj;" after acquiring the synch lock.

Suggested fixes inline below.

But do consider Effective Java 2nd edition, Item 71 (Use lazy initialization
judiciously) before making all your fields lazy this way, and consider that
the extra level of indirection that you're introducing here might dominate
whatever savings you were hoping to get from lazy initialization over
straightforward synchronization.

--tim

On Tue, Jun 23, 2009 at 5:03 PM, Ashley Williams <ashpublic at mac.com> wrote:

> @ThreadSafe
> public abstract class LazyField<T> implements Callable<T> {
> private volatile T obj;
>

           public abstract T call();


> public T get() {
> // use a local variable to save on multiple reads of a volatile
> T result = obj;
> if (result == null) {
> synchronized (this) {
>

                                   result = obj;


> 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/b3f47ef2/attachment-0001.html>


More information about the Concurrency-interest mailing list