2

Hello I would like to know how to properly get singleton instances and what is best practice?

public class SingeltonTest {

    private static final CounterSingelton COUNTER = CounterSingelton.getInstance();

    public static void main(String[] args) {

        //Type A
        for (int a = 0; a < 100; a++) {
            COUNTER.increase();
        }

        //Type B
        for (int a = 0; a < 100; a++) {
            CounterSingelton counter = CounterSingelton.getInstance();
            counter.increase();
        }

        //Type C
        for (int a = 0; a < 100; a++) {
            CounterSingelton.getInstance().increase();
        }
    }
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
J. Doe
  • 33
  • 3
  • 1
    Possible duplicate of [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) – blank Nov 12 '15 at 08:31
  • one of the answers mentioned it! don't use static Singelton, just get it when it is needed, usually getting Singeltons must not be a big deal "performance-wise" (unless we are talking about getting the Singelton for the first time considering that the creation process of this Singelton is heavy process that may take long time ) – Ahmad Hajjar Nov 12 '15 at 08:47

1 Answers1

2

Best practice is to avoid static Singleton and replace them by contextual Singleton.

Common pattern for static Singleton access is using a static getInstance() method. Which can be easily change to factory method or complex initialization process without changing signature.

However, if signature doesn't change, behaviour does. So it might require changing code at caller site.

Type B and Type C are strictly equivalent. Only Type A may be broken (in future) due to change in internal state of the class (such as lazy loading).

LoganMzz
  • 1,597
  • 3
  • 18
  • 31