6
|
Here is an example of why
volatile is necessary. If you remove the keyword volatile , thread 1may never terminate. (When I tested on Java 1.6 Hotspot on Linux, this was indeed the case - your results may vary as the JVM is not obliged to do any caching of variables not marked volatile .)
| ||||||||||||||||||||
|
1
|
The volatile keyword is pretty complex and you need to understand what it does and does not do well before you use it. I recommend reading this language specification section which explains it very well.
They highlight this example:
What this means is that during
one() j is never greater than i . However, another Thread runningtwo() might print out a value of j that is much larger than i because let's say two() is running and fetches the value of i . Then one() runs 1000 times. Then the Thread running two finally gets scheduled again and picks up j which is now much larger than the value of i . I think this example perfectly demonstrates the difference between volatile and synchronized - the updates to i and j are volatile which means that the order that they happen in is consistent with the source code. However the two updates happen separately and not atomically so callers may see values that look (to that caller) to be inconsistent.
In a nutshell: Be very careful with
volatile ! |
volatile
(and many other concurrency-related aspects) are very hard to demonstrate, because if you use them wrongly, then they may still appear to work correctly and not show a problem until a very specific condition occurs and leads to a problem. – Joachim Sauer Apr 28 '11 at 10:05