[concurrency-interest] RE: Concurrency-interest Digest, Vol 4, Issue 4

David Holmes dholmes at dltech.com.au
Wed May 4 19:36:32 EDT 2005


> Thank you for all your replies. With all these,  I guess, I will be able
> convince my tech lead.
> I have a question though, about On Demand Holder Idiom. If the
> constructor of Singleton is throwing exception, we will not be able to
> use it?
> public class Cache {
>
>
>   private static class OnDemandHelher {
>        static Cache instance = new Cache(); ///
>   }
>
>   private Cache() throws InitializationException {
>     //load data...
>   }
>
> }

Presuming that is a checked-exception, you would have to catch and convert
to an unchecked exception:

    private static class OnDemandHelper {
        static Cache instance;

        static {
           try {
               instance = new Cache();
           }
           catch (InitializationException e) {
              throw (RuntimeException) new RuntimeException().initCause(e);
           }
        }
    }

Or you could create your own subclass of RuntimeException to handle this
directly. Of course you would have to adapt the handling of the exception in
the client code.

You could also account for the exception in the helper another way:

    private static class OnDemandHelper {
        static Cache instance;
	 InitializationException exception;

        static {
           try {
               instance = new Cache();
           }
           catch (InitializationException e) {
              exception = e;
           }
        }

        static Cache instance() throws InitializationException {
           if (instance != null)
              return instance;
           throw exception;
        }
    }

This way client code still uses an instance() method that can throw, but
that method is no longer responsible for initialization.

Cheers,
David Holmes



More information about the Concurrency-interest mailing list