[concurrency-interest] Significance of volatile for Objects

Pavitar Singh pavitar at pramati.com
Fri Mar 7 06:19:43 EST 2008


Hi,

Thanks for your explanations.

When i read JMM about Happens Before Relationships:

It says:

A write to a volatile field happens before every subsequent read of that
volatile.

But then doing operation on HashMap like put. It doesnt mean write to the
volatile field.Siimilarly a get shouldnt mean read from volatile.Is it
correct or i am missing something here.


Regards
Pavitar


> Volatile helps to prevent 2 issues:
>
> reorderings
> visibility.
>
> Reordering:
> it prevents that the created hashmap is assigned to the data variable,
> before the constructor has run. So it prevents other threads from
> seeing a partly constructed hashmap.
>
> Visibility:
> It makes sure that thread that reads data, sees the most recently
> written value of data. It also makes sure that the reading thread sees
> all values written (e.g. the member variables of the hashmap) before
> the writing thread did the write to data. This last behavior is
> available since Java 1.5 (JMM 133). It is a technique that can be used
> to 'transfer' objects from one thread to another in a thread safe
> manner. A BlockingQueue for example support this behavior.
>
> For more information I suggest "Java Concurrency in Practice"
>
> PS:
> I know you made the remark, but for other less experienced developers
> reading this thread.. the example is not threadsafe because HashMap is
> not threadsafe. So its internal structure could be corrupted by
> concurrent access.
>
> On Fri, Mar 7, 2008 at 10:04 AM, Pavitar Singh <pavitar at pramati.com>
> wrote:
>> Hi,
>>
>>  If i have something like this:
>>
>>  volatile Map data = new HashMap();
>>
>>  then what are the gurantees provided by volatile.
>>
>>  I know this is wrong usage of volatile. But i just wanted to know
>>  gurantees provided by volatile in case of Objects.
>>
>>  Regards
>>  Pavitar
>>  _______________________________________________
>>  Concurrency-interest mailing list
>>  Concurrency-interest at altair.cs.oswego.edu
>>  http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>



More information about the Concurrency-interest mailing list