Reputation: 6355
As in the title - is there any case in which volatile is useful in the context of single-thread programming in Java? I know it's used to make sure the value of the variable is always actually checked in memory so is there any case in which that value may change (in a singlethreaded application) in a way that the app/compiler won't notice?
Upvotes: 1
Views: 547
Reputation: 11609
It is not useful from the point of view described in the question, but it can affect code execution:
Happens-before semantics make restrictions for program instruction reordering. Usually if you have
private int a;
private int b;
private boolean ready;
void calc(int x, int z) {
a = x + 5;
b = z - 3;
ready = true;
}
JIT compiler is allowed to execute method instructions in any order (for performance reasons).
But if you add volatile keyword: private volatile boolean ready
, then its guaranteed that first two operations would be executed before true
will be assigned to ready
variable. This is still pretty useless, but technically there is a difference.
Upvotes: 1