How to make immutable singleton in Java?

An immutable object is initialized only by its constuctor, while a singleton is created by the static method. How to make immutable singleton in Java?

+4
source share
4 answers

while a singleton is instantiated by a static method

Although this is a common way to do this, this is far from the only way.

In Java 1.5, the new version of Singleton is a one-time renaming pattern:

public enum Elvis{ INSTANCE // this is a singleton, no static methods involved } 

And since enumerations can have constructors, methods, and fields, you can provide them with all the immutable state you want.

Link:


In addition, the term Singleton leaves room for interpretation. Singleton means that for a certain area there is exactly one object, but the scope can be several:

  • Java VM Classloader (thanks @ Paŭlo Ebermann for reminding me): in this case use enums or Initialize-static-inner class . This, of course, is what is usually meant by a single.
    Be careful: enumerations and all other singletones are broken if they are loaded through multiple class loaders.
  • Enterprise Application (in this case, you need a container-controlled singleton such as Spring singleton bean ). This can be several objects on a VM or one object on several virtual machines (or one object on a virtual machine, of course).
  • Theme (use ThreadLocal )
  • Request / Session (you will need a container to manage this Spring , Seam , and some others can do it for you)
  • Did I forget something?

All of the above can be done unchanged, each in its own way (although for components controlled by containers, it is usually not easy)

+7
source

The solution pointed out by Shen is a good way to initialize singletons if creating them is not expensive. If you want a lazy boot look at initializing idioms on demand.

  // from wikipedia entry public class Singleton { // Private constructor prevents instantiation from other classes private Singleton() { } /** * SingletonHolder is loaded on the first execution of Singleton.getInstance() * or the first access to SingletonHolder.INSTANCE, not before. */ private static class SingletonHolder { public static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } 
+5
source
 public enum MySingleton { instance; //methods } //usage MySingleton.instance.someMethod(); 
+1
source

You are unnecessary. To be immutable, an object must be unmodified after its creation. This is usually interpreted as “modifiable only in the constructor”, but if you have to create it in a different way that will still make it immutable. As long as your object cannot be modified after its initialization, it is immutable. You might consider installing a Singleton instance as part of the initialization.

Most immutability benefits are not related to singletones.

+1
source

Source: https://habr.com/ru/post/1338267/


All Articles