1

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?

AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
NPS
  • 6,003
  • 11
  • 53
  • 90
  • Not in any case that I can think about. – Maroun Feb 04 '16 at 11:37
  • I am not sure about authenticity of [this website](http://www.javamex.com/tutorials/synchronization_volatile_when.shtml) but it lists very clearly the situations when `volatile` has no use and your case is one of those items. – Sabir Khan Feb 04 '16 at 11:39

2 Answers2

5

No, at least not for your own defined variables in a single-threaded application.

The volatile keyword guarantees happens-before relationships with multiple reads of that variable, which only makes sense when multiple threads access it.

Additional insights here.

Mena
  • 47,782
  • 11
  • 87
  • 106
1

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.

AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
  • Re _technically there is a difference_, There may be a difference under the hood, but if adding `volatile` to your example makes a difference in the outcome of a single threaded program, then the Java/JVM implementation is defective. – Solomon Slow Feb 04 '16 at 14:33
  • @jameslarge i didn't say that. example shows difference for JIT instruction reordering. – AdamSkywalker Feb 04 '16 at 14:38