NPS
NPS

Reputation: 6355

Is volatile useful at all in a singlethreaded application in Java?

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

Answers (2)

AdamSkywalker
AdamSkywalker

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

Mena
Mena

Reputation: 48404

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.

Upvotes: 5

Related Questions