Inquisitive
Inquisitive

Reputation: 7856

What makes initializing an object reference from a static initializer to publish the object safely?

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 :

  1. Is this a really a way of safe publication ?
  2. If the answer to 1 is no then why ? If yes, then also please explain why ?

Upvotes: 2

Views: 380

Answers (3)

Brian Agnew
Brian Agnew

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:

  1. not use a singleton. See here for more details on the difficulties of using singletons. I note that your question is tagged with thread-related keywords, and singletons create atheir own particular issues with threading.
  2. let the client class control the initialisation of this object. You may wish to defer initialisation of this object (imagine if it suddenly becomes a heavyweight object, performs network calls upon construction etc.). Currently the above provides very little control over this.

Upvotes: 1

Peter Lawrey
Peter Lawrey

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

assylias
assylias

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

Related Questions