0

Why do we need volatile on primitives? The most common example that I found was that:

volatile boolean shutdownRequested;

...

public void shutdown() { shutdownRequested = true; }

public void doWork() { 
    while (!shutdownRequested) { 
        // do stuff
    }
}

But when I been trying to run it by myself. Volatile declaration changed nothing. It stops with both volatile and not volatile shutdownRequested

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216

5 Answers5

4

Essentially, volatile is used to indicate that a variable's value will be modified by different threads.

a volatile Java variable means:

The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"; and access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

Biswajit
  • 2,434
  • 2
  • 28
  • 35
2

Variables not marked volatile can be cached as much as the JVM wishes. For example, a copy of the variable could be loaded into a register and may then never refer to the original instance variable, especially in a tight loop.

Marking it as volatile tells the JVM that it must always refer to the original instance variable.

What you are seeing is probably just the JVM not cacheing the variable, even though it is allowed to.

This is one of the reasons why multi-threaded code is difficult to prove correct. Not only will not all JVMs work in the same way but you may even get different results when debugging your code compared to when you run it and it may run differently again if it is running on a multi-core unit..

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

volatile is useful for multi-threaded code.

See this question: Do you ever use the volatile keyword in Java?

Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

Changes to a volatile variable are always visible to other threads. enter link description here

In your example where one thread is executing doWork() and another comes along and calls shutdown. On some JVMs on some platforms the compiler may optimise things in such a way that the change to the shutdownRequested variable is not seen by the worker thread e.g. the variable may be cached in a register.

brain
  • 5,496
  • 1
  • 26
  • 29
0

You should use volatile variables when you want to make sure that the value being read is the current value, without any cache.

Rodrigo Sasaki
  • 7,048
  • 4
  • 34
  • 49