O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

There's more...

The volatile keyword only works well when the value of the shared variable is only modified by one thread. If the variable is modified by multiple threads, the volatile keyword doesn't protect you from possible data-race conditions. It also doesn't make operations, such as + or -, atomic. For example, the ++ operator over a volatile variable is not thread-safe.

Since Java 5, Java Memory Model has a happens--before guarantee established with the volatile keyword. This fact has two implications:

  • When you modify a volatile variable, its value is sent to the main memory. The value of all the variables modified previously by the same thread are sent too.
  • Compilers can't reorder sentences that modify a volatile variable for an ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required