Skip to Content
Java Projects - Second Edition
book

Java Projects - Second Edition

by Peter Verhas
August 2018
Intermediate to advanced
524 pages
14h 45m
English
Packt Publishing
Content preview from Java Projects - Second Edition

Volatile variables

Let's modify the declaration of the o variable in our sample code as follows:

private volatile Object o = null;

The preceding code runs fine and stops after a second or so. Any Java implementation has to guarantee that multiple threads can access volatile fields and the value of the field is consistently updated. This does not mean that volatile declaration will solve all synchronization issues, but guarantees that the different variables and their value change relations are consistent. For example, let's consider that we have the following two fields incremented in a method:

private int i=0,j=0; 
  
 public void method(){ 
     i++; j++; 
 }

In the preceding code, reading i and j in a different thread may never result in i>j. Without ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java 11 Cookbook - Second Edition

Java 11 Cookbook - Second Edition

Nick Samoylov, Mohamed Sanaulla

Publisher Resources

ISBN: 9781789131895Supplemental Content