Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final reference to an object when constructing it

Tags:

java

Say I have a reference to some class and it is final like:

public final Mycalss ref;

and MyClass has several attributes (not final ones). Now when I construct MyClass object like this:

ref = new MyClass( some arguments);

Does it mean that other threads can safely see the content of Myclass since it is final referenced?

like image 975
user1409534 Avatar asked May 19 '15 09:05

user1409534


3 Answers

Making a reference final means once you assign an object to that reference, you cannot assign some other object to that reference.

But you can change the values of that same object even if the reference is declared as final.

Like :

public final Myclass ref;
ref = new Myclass();

//this is not allowed
ref = new MyClass();   //since you have already assigned an object to your final reference

//this is allowed
ref.setSomeProperty("abc"):

For answer on threading and final, see @Erwin Bolwidt answer.

like image 101
Abubakkar Avatar answered Oct 10 '22 04:10

Abubakkar


From the Java Language Specification section 17.5:

The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.

(My emphasis added)

This is part of the "Threads and Locks" section 17 of the JLS, of which also the Java Memory Model specification is part.

Yes, you are correct. This is a correct way to safely construct objects.

like image 32
Erwin Bolwidt Avatar answered Oct 10 '22 05:10

Erwin Bolwidt


As others said final means that only one assignment to this variable can ever occur. However, in multithreading environment, if thread A access the object before thread B made the assignemnt, thread A will see null. It means that thread A can see two different values of the variable.

Also, you should remember about Memory Consistency Errors - i.e. that changes made to on object by one thread may not be visible to the other thread. I would recommend to do some reading on synchronisation and volatile keyword - this is a good place to start.

like image 25
Jaroslaw Pawlak Avatar answered Oct 10 '22 06:10

Jaroslaw Pawlak