Object publication: Enables an object to be used in code outside the current scope
How can I safely publish an object?
1: mutable objects such as the release by means of locking
2: Immutable objects can be freely released
A mutable object must be published in a secure manner, which means that the thread that publishes and uses the object must use synchronization.
To secure a publishing object, the state of the object and the reference to the object must be visible to other threads, common practices include:
1: Initializing an object reference in a static initialization function
2: Save the object's reference to a volatile type field
3: Save the object's reference to the correct constructed object's final field
4: Save the object's reference to a lock-protected domain
5: Using a thread-safe container
6: The simplest and safest way to use statically constructed objects is to use static initializers.
public static Holder Holer = new Holder (23);
The reason is that the static initializer is performed by the JVM during the initialization phase of the class, and because there is a synchronization mechanism inside the JVM, any objects that can be initialized in this manner can be safely published.
How to safely publish an object