Reputation: 7856
Consider the following code :
// This code safely publishes the Publishable object
public static Publishable publishable= new Publishable();
I have seen such a way of publishing the custom Publishable object and I read that this is safe. My question is :
Upvotes: 2
Views: 380
Reputation: 272367
I don't think it's a particularly good way of initialising this object (leaving aside the word 'safe', which I could interpret in may ways).
It's creating a singleton tied to the containing class, and the initialisation isn't controlled. Or rather, it initialises as soon as that class is loaded. Do you have complete control over that ?
I would rather:
Upvotes: 1
Reputation: 533780
All code which is run from a static block or initialised staticly is thread safe.
I would make the field final if you can.
public static final Publishable publishable= new Publishable();
or even make the Publishable an enum
public enum Publishable {
INSTANCE;
}
Upvotes: 3
Reputation: 328785
According to JCiP:
static initializers are executed by the JVM at class initialization time [...] this mechanism is guaranteed to safely publish any objects initialized in this way.
Reference: JLS 12.4.2 - item 9:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
Upvotes: 7