Guifan Li
Guifan Li

Reputation: 1663

Why final key word can guarantee safe publication if constructor is not synchronized?

The book Java Concurrency in Practice mentions that

A properly constructed object can be safely published by:

Storing a reference to it into a final field of a properly constructed object

Firstly, I thought because a final field can only be initilized in the class constructor and Java constructor is implicitly "Synchronized". However, I realized that this is not the case.

class Student{
   int student_id;
   public Student(int i){
       student_id = i;
   }
}

class Test {
   private final Student student;
   public Test(){
         student = new Student(1);
         ...
   }
}

For example, the above code how can JVM guarantee student is a safe publication?

What about it is a static final?

class Test {
       private static final Student student;
       public Test(){
             student = new Student(1); //will this be partially constructed when the other thread reads a bad object ?

             ...
       }
    }

Does final itself imply something so that Jave Memory Model will guarantee the same publication ?

Upvotes: 3

Views: 137

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533750

JVM guarantee student is a safe publication?

There is a number of ways to ensure safe publication, usually using a write barrier will be enough. In any case, however the JVM it is must guarantee this for the processor it is running on.

What about it is a static final?

All static field are initialised in a single threaded manner. Class initialisation is thread safe whether you use final or not.

Does final itself imply something so that Jave Memory Model will guarantee the same publication ?

Except for constructors, not really. It is easier to support safe publication of a value which should not change.

Upvotes: 1

Related Questions