I dont understand those few statements that I read:
because accessing a volatile variable never holds a lock, it is not
suitable for cases where we want to read-update-write as an atomic
operation (unless we’re prepared to “miss an update”);
What does it mean, I cant read-update-write?
When will I want to use volatile instead of simple boolean. In C#, I remember that I could use a simple static bool to control when a thread starts and stops, but in java I need to use the identifier, “volatile”:
> public class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}
}
public void tellMeToStop() {
pleaseStop = true;
}
}
The sentence speaks about this example:
Although the
counterhasvolatilemodifier, it is not guaranteed that if two threads access theincrement()method that two different integers will be returned. Because thecounter++operation is not atomic. It isget, increment, return. It is possible that two threads callincrement()at the same time and that the first thread is at thegetphase and the second thread is at thegetphase before the first thread is at theincrementphase.Summary:
volatiledoesn’t guarantee atomicity or whatever. It just guarantees that when you access the variable, you will not receive an old cached value. But it doesn’t guarantee any thread safety or atomicity.