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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With