Shivam Sinha
Shivam Sinha

Reputation: 5150

When not to use volatile variable in Java

I understand the volatile variables only guarantee visibility and should not be used for atomic/compound operations. However I think I read some where that it can also be used only if one thread is updating the value (in a single operation). Is this correct ?

So if two threads are updating a volatile variable say boolean flag is this thread safe ?

Upvotes: 3

Views: 863

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

I understand the volatile variables only guarantee visibility and

correct

should not be used for atomic/compound operations.

Actually all the AtomicXxxx classes use volatile. They use it in a safe manner which is the important difference. Not all operations are safe.

I think I read some where that it can also be used only if one thread is updating the value. Is this correct ?

That is one solution. If you have only one writer, using volatile is fine for that field.

Note: it is s common misconception that volatile confers thread safety for any operation which uses it. e.g.

volatile int[] a = { 0 };

a[0]++; // not thread safe even if you have only 1 writer.

This is because writes to a and only a are volatile. Anything which a points to is not also volatile This is no different to final

final int[] a = { 0 };
a = null; // cannot do this
a[0] = 1; // compiles fine, is not final.

I have narrowed down the scenario for you: if two threads are updating a volatile variable say boolean flag (in a single operation e.g. set it to true or false) and without any other form of synchronizatio,n is this thread safe ?

It is only safe if you have one writer, or they are both setting to the same value. For example

flag = true; // ok, provided no thread sets it to false.
flag = !flag; // not ok.

Upvotes: 5

Related Questions