[concurrency-interest] Visibility of lazy intialisation

Mike Quilleash mike.quilleash at subexazure.com
Tue Jul 18 11:01:15 EDT 2006

I will only ever access the helper through getHelper() and Helper itself
can assumed to be threadsafe.  I just wonder if the following is

1) getHelper() is called 
2) helper == null
3) localHelper created
4) helper = localHelper
5) localHelper.initialise()

Note 4 and 5 are out of order.  Can this happen or not?  I'm worried
about .initialise() throwing an exception and if it does can it leave
the helper variable not-null.


-----Original Message-----
From: Giuliano Mega [mailto:giuliano.mega at gmail.com] 
Sent: 18 July 2006 15:18
To: Mike Quilleash 
Cc: concurrency-interest at cs.oswego.edu
Subject: Re: [concurrency-interest] Visibility of lazy intialisation

Hi Mike,

I may be wrong (in which case I'm sure I'll be corrected briefly), but
since correctly synchronized programs should appear to execute in
program order, I don't think that 'helper' could appear as non-null to
anyone (at least not in calls to 'getHelper'). You have to ensure,
however, that every access to helper occur inside a synchronized block
that refers to the same lock.

Best regards,

On 7/18/06, Mike Quilleash <mike.quilleash at subexazure.com> wrote:
> I have a static singleton that I want to lazy initialise.
> Currently the code I have looks like this
> private static Helper helper = null;
> public synchronized static Helper getHelper() throws HelperException {
>   if ( helper == null )
>   {
>     Helper localHelper = new Helper();
>     localHelper.initialise();
>     helper = locaHelper;
>   }
>   return helper;
> }
> The initialise() function may throw an exception which I want to 
> propogate up and catch somewhere higher.  I'm wondering if it 
> definately the case that the helper variable will NOT be null if an 
> exception is thrown in the Helper constructor or initialise().  Can 
> the JVM/OS/CPU reorder the instructions so that helper is set before
initialise is executed?
> Should I instead be using one of the static initialise idions, like a 
> static class?  My problem would then become how to catch the 
> initialise when it is in a static code block.
> Cheers for any help/advice.
>  This e-mail is bound by the terms and conditions described at 
> http://www.subexazure.com/mail-disclaimer.html
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest

Giuliano Mega <giuliano at ime.usp.br>

 This e-mail is bound by the terms and conditions described at http://www.subexazure.com/mail-disclaimer.html

More information about the Concurrency-interest mailing list