Question

Is it necessary to Assert.notNull of a Singleton Object?

I have a class:

public class ComponentFactory {
    private static LibraryFrame libraryFrame;

    public static synchronized LibraryFrame getLibraryFrame() {
        if (libraryFrame == null) {
           libraryFrame = new LibraryFrame();
        }
        return libraryFrame;
    }
}

Now is it needed to use as:

LibraryFrame libraryFrame = ComponentFactory.getLibraryFrame();
Assert.notNull(libraryFrame);
// other part

Here Assert class is org.springframework.util.Assert.

If Assertion failed is there anyway to call System.exit(0) after failure occurred?

Was it helpful?

Solution

The Assert is not necessary since the LibraryFrame instance will always be initialized at this point.

OTHER TIPS

According to the documentation for that class, it's really intended to be used by a method to valid its arguments. (That is, it's intended for the enforcement of preconditions.) You should have unit-tests for ComponentFactory, and they should assert that its static getLibraryFrame() method doesn't return null, but it's not worthwhile to assert this at run-time.

Well when you use the Assert class from JUnit, any method in there are all void, but it uses the JUnit framework to tell you if the test has pass or failed.

If this is method for unit testing, then you have accomplished your test, but if this were ment for runtime, then use a if condition.

I recommend using the initialization-on-demand pattern (i.e. lazy loading singleton) for your singleton. In that pattern if the construction of the instance fails you'll get an exception, otherwise you'll get the object.

This improves on your solution in two ways: it doesn't have the overhead of synchronization and it doesn't have the overhead of the Assert. Both methods throw an exception if the singleton object is not created - in your code you'll get an IllegalArgumentException from the assert.

Using init-on-demand your code would be:

public class ComponentFactory 
{
  private ComponentFactory() 
  {
  }

  private static class LazyHolder 
  {
    public static final LibraryFrame INSTANCE = new LibraryFrame();
  }

  public static LibraryFrame getLibraryFrame() 
  {
    return LazyHolder.INSTANCE;
  }
}

To use it would still be:

LibraryFrame libraryFrame = ComponentFactory.getLibraryFrame();

...except you no longer need neither the Assert nor the Synchronized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top