Does volatile need for int type in Java? As I understand 32bit-platform read/write 4bytes type data as atomic. Could I get issue if I will use int data type in concurrency program?
-
You can use [`AtomicInteger`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html) – px06 Dec 07 '16 at 10:44
-
3`volatile` is not only about atomic operations. See this: http://stackoverflow.com/questions/106591/do-you-ever-use-the-volatile-keyword-in-java – Thorsten Dittmar Dec 07 '16 at 10:44
2 Answers
Consider the following code:
class Demo {
int value;
void foo() {
while (value == 0);
System.out.println("Done!");
}
}
Even if you change value
to some non-zero value from a different thread, there is no guarantee that the loop will ever complete. Because value
isn't atomic, the loop might be optimized to (effectively):
if (value == 0)
while (true);
hence an infinite loop occurs if value
happens to be zero when foo()
is first called.
But if you make value
volatile
, this optimization cannot be made.

- 137,514
- 11
- 162
- 243
Volatile is not used for atomic operations, but for visibility. If any changes has been made and it should be visible for other threads, volatile should be used. Here is a short description by java tutorial:
Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

- 86
- 4