Synchronized block

Declaring variables is not the only tool for ensuring 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, which is inside a method, constructor, or initializer block.

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 the 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 ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.