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
About the Author
About the Reviewer
Customer Feedback

Synchronized block

Declaring variables are not the only tool to ensure the consistency between threads. There are other tools in the Java language and one of them is the synchronized block. The synchronized keyword is part of the language and it can be used in front of a method or a program block inside a method.

Every object in the Java program has a monitor that can be locked and unlocked by any running thread. When a thread locks a monitor, it is said that that thread holds the lock, and no two threads can hold the lock of a monitor at a time. If a thread tries to lock a monitor that is already locked, it gets BLOCKED until the monitor is released. A synchronized block starts with the synchronized keyword, and then an object instance specified between parentheses and the block comes. The following small program demonstrates the synchronized block:

public class SynchronizedDemo implements Runnable { 
     public static final int N = 1000; 
     public static final int MAX_TRY = 1_000_000...