[concurrency-interest] RE: Synchronization of data readby multiple threads

Dawid Kurzyniec dawidk at mathcs.emory.edu
Sun Oct 30 13:33:47 EST 2005

Jeremy Manson wrote:

> Ryan LeCompte wrote:
>> Okay, that sounds fine. However, what about if the main thread (the
>> one that instantiated Test) continues to read values that were set in
>> the constructor? For example, if the main thread does:
>> t.isInstantiated() later on, will it continue to return the value
>> that was set in the constructor when Test was instantiated? Keep in
>> mind that in this particular scenario the values that the main thread
>> will read never change after being initially set in the constructor
>> of Test. There is no need for making the 'instantiated' variable
>> volatile in this case, right?
> Are you asking, "If one thread sets a field, and then later reads that 
> field, do I have to do additional synchronization?"  The answer to 
> that is no.  You don't need synchronization if you are only dealing 
> with one thread.
> By the way, if you are setting a field once, in the constructor, and 
> then never changing it, then it is a good idea to make the field 
> final.  All reads of final fields return the correctly constructed 
> value, without synchronization (unless a reference to the constructed 
> object escapes the constructor, or you are using some weird custom 
> deserialization protocols).
And again, if this field is final, it means it is not needed here at 
all. Its value is always true, so isInstantiated() always returns true, 
so the test in the run() method will always yield true. If you managed 
to invoked an instance method on an object, it means that this object 
has been instantiated.

The existence of a final field like this does only have sense if you set 
it to different values in the constructor, e.g. depending on constructor 
parameters. But if you always set it to true, you can as well get rid of it.


More information about the Concurrency-interest mailing list