[concurrency-interest] syntax sugar for lazy instantiation

Ashley Williams ashpublic at mac.com
Tue Jun 23 17:30:21 EDT 2009


I should have mentioned that I am using the aspectj softened  
exceptions feature.

But if there is a requirement that a field should be lazily  
instantiated, is there really any advantage when using intrinsic  
locking - other than cleaner syntax?
I'm still under the impression that for the post-initialization path  
the double checked lock technique is quicker - namely because there is  
no lock.

Also this mailing list doesn't seem to be updating in order of sent  
message.

On 23 Jun 2009, at 22:19, Tim Peierls wrote:

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


More information about the Concurrency-interest mailing list