Below are the following cases which you can consider while implementing the singleton -
Case 1 : If there is no memory constraint & initialization will not take much time.
then go with eager initialization like -
public static Singleton singleton = new Singleton();
And make the constructor as private.
Case 2 : If the properties of the singleton class can't be provided during
construction then can try for Case 3 solution.
Case 3 : If memory constraint is applicable & initialization takes time, then go with
lazy initialization by providing one public static method that returns the
instance & once created then every time that instance will be returned by
that method.
Case 4 : If multithreaded environment is applicable & case 3 constraints are not
present then use case 1 solution, it is best in such cases.
Case 5 : If multithreaded environment is applicable & case 3 constraints are also
applicable then double checked locking concept can be used but also
check this & this. And I think that using static/class variable should resolve
other issues as pointed here.
Case 6 : In multithreaded environment, if you are still eager to code your singleton
class then look to override readResolve() & writeReplace() methods.
Case 7 : If you are using jdk5 & above, then use enum directly without taking above
pains.
And I think that there is no such thing called singleton across multiple JVMs.
Next
Case 1 : If there is no memory constraint & initialization will not take much time.
then go with eager initialization like -
public static Singleton singleton = new Singleton();
And make the constructor as private.
Case 2 : If the properties of the singleton class can't be provided during
construction then can try for Case 3 solution.
Case 3 : If memory constraint is applicable & initialization takes time, then go with
lazy initialization by providing one public static method that returns the
instance & once created then every time that instance will be returned by
that method.
Case 4 : If multithreaded environment is applicable & case 3 constraints are not
present then use case 1 solution, it is best in such cases.
Case 5 : If multithreaded environment is applicable & case 3 constraints are also
applicable then double checked locking concept can be used but also
check this & this. And I think that using static/class variable should resolve
other issues as pointed here.
Case 6 : In multithreaded environment, if you are still eager to code your singleton
class then look to override readResolve() & writeReplace() methods.
Case 7 : If you are using jdk5 & above, then use enum directly without taking above
pains.
And I think that there is no such thing called singleton across multiple JVMs.
Next