There is an example in JLS about the keyword volatile.
One thread repeatedly calls the method one, another thread calls the method two.
class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}
This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.
Some questions:
- What does
shared values
mean? - In which scenario should we use
volatile
?(since "any given invocation of method two might observe a value for j that is much greater than the value observed for i")
I learned from other articles that if there is more than one core or processor (I think the point is more than one cache), an "unvolatile" value may cause problems.
What is the problem? And why?