Book Image

Java 9 Programming By Example

By : Peter Verhas
Book Image

Java 9 Programming By Example

By: Peter Verhas

Overview of this book

This book gets you started with essential software development easily and quickly, guiding you through Java’s different facets. By adopting this approach, you can bridge the gap between learning and doing immediately. You will learn the new features of Java 9 quickly and experience a simple and powerful approach to software development. You will be able to use the Java runtime tools, understand the Java environment, and create Java programs. We then cover more simple examples to build your foundation before diving to some complex data structure problems that will solidify your Java 9 skills. With a special focus on modularity and HTTP 2.0, this book will guide you to get employed as a top notch Java developer. By the end of the book, you will have a firm foundation to continue your journey towards becoming a professional Java developer.
Table of Contents (17 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

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 we have the following two fields incremented in a method:

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

In the preceding code, reading i and j from another thread will never result an i>j. Without the volatile declaration, the compiler is free to reorganize the execution of the increment operations if it needs and thus, it will not guarantee that an asynchronous thread reads consistent values.