[ACCEPTED]-Singleton and Exception-singleton

Accepted answer
Score: 37

Use a static initializer and rethrow the 8 Exception as ExceptionInInitializerError. Click the link to read the Javadoc, you'll 7 see that it suits exactly for this particular 6 functional requirement: handling exceptions 5 during static initialization. A singleton is in fact nothing 4 less or more than a statically and lazily 3 initialized global object.

private static class SingletonObjectFactoryHolder{
    private static final ObjectFactory INSTANCE;
    static {
        try {
            INSTANCE = new ObjectFactory();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
}

No need for double checked locking idiom 2 which is considered an anti-pattern and 1 in some circumstances even unsafe.

More Related questions