Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency in Practice - volatile ++

In Concurrency in Practice, it says you can use volatile variables if

Writes to the variable do not depend on its current value.

So, if you have a shared, mutable variable a, and all threads ever do to it is go a++ (they don't get the value, they just ++).

Then according to the quote, you should be able to make it volatile even though a++ is not atomic, correct?

like image 942
Sam Adamsh Avatar asked Nov 04 '12 16:11

Sam Adamsh


People also ask

Is Java Concurrency in Practice still valid?

TL: DR — Yes, Java Concurrency in Practice is still valid and one of the best books to learn Java multithreading and concurrency concepts.

Is Threadsafe volatile?

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem.

What is the difference between volatile and synchronized?

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

Is volatile required with synchronized?

If it is accessed only from synchronized blocks is not needed the volatile keyword. Synchronized guarantees that changes to variables accessed inside the synchronized block are visible to all threads entering a synchronized block.


2 Answers

No, using ++ on a volatile variable is not threadsafe, because

a++

is equivalent to:

int temp = a;
temp = temp + 1;
a = temp;

So the write back to a may happen after another thread has modified a since your thread read it, so a++, even if a is volatile, is not threadsafe.

You can use AtomicInteger, which implements threadsafe atomic incrementation.

like image 159
Bohemian Avatar answered Nov 02 '22 17:11

Bohemian


a++ reads the value of a, since it's equivalent to

  • read a
  • increment the read value
  • assign the new value to a

So no, you can't safely use a volatile variable in this case.

like image 27
JB Nizet Avatar answered Nov 02 '22 16:11

JB Nizet