Re: JavaMemoryModel: [Fwd: double check article: what if constructor throws exception]

From: Bill Pugh (pugh@cs.umd.edu)
Date: Tue Jun 12 2001 - 20:20:57 EDT


At 5:01 PM -0700 6/12/01, Kammy Wesley wrote:
>Kammy Wesley wrote:
>>
>> Hello all:
>>
>> I have read the article on "Double Checked Locking is Broken", and I
>> have a question. If the constructor for my singleton throws an
>> exception, do I have any other choice besides the synchronized
>> "getHelper" method for correctly instantiating my singleton?
>>
>> It doesn't seem that I can use the "create another class to hold the
>> singleton method" as referred to near the end of the article, right?
>>
>> http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
>>
>> thanks,
>>
> > Kammy

Sure you can. Just use a static code block to initialize it:

class Singleton {
   static final Helper h;
   static {
     Helper tmp = null;
     try {
       tmp = new Helper();
       }
     catch (FooException f) {
       }
     h = tmp;
     }
   }

(By the way, I had to check if the system allows static blank finals
(e.g., final static fields assigned in a static code block; javac
seems happy with it, although I didn't check the specification).

Bill

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:32 EDT