[Solved] Static class instance inside class


What you have there is a static method getLibrary() that returns the same instance for all callers. That’s called a Singleton – although there’s better ways to code them.

Then again your supposed Singleton (TestLibrary) exhibits methods that when called change internal state – most important, the ErrorHandler.

This will cause strange behaviour, especially in multithreaded systems.

Code like this:

TestLibrary.getLibrary().run("".split(""));
ErrorHandler eh = TestLibrary.getErrorHandler();
assertEquals(eh, TestLibrary.getErrorHandler());

might fail. Because someone (meaning: some other thread) might have just happend to call init() between lines 2 and 3, causing ErrorHandler to be set to just another value.

If you need to initialize your TestLibrary before use, you should do it once, and once only – so you’re better of putting this into the constructor of TestLibrary.

If you need TestLibraries that are intialized different throughout your code, you should remove the Singleton pattern and stick to plain

  TestLibrary tl = new TestLibrary();
  tl.run("".split(""));

Read more about Singleton in What is an efficient way to implement a singleton pattern in Java?

1

solved Static class instance inside class