Java – Thread Synchronization3 min read

Having multiple threads in a program may cause inconsistency and thread interference, that is the multiple threads when trying to access the same resource. One thread may try to write and another may try to read the shared resource or same file. So to achieve the use of only one resource or file at a time, we use synchronization.

Synchronization makes sure that only one out of the multiple threads is allowed to access the resource at a given time.

In this process, comes the Lock Concept, also known as monitors.
Each object created in java is provided with the monitor. Only one thread may hold the lock at a time through which thread can lock or unlock.

Synchronized method in java:

Java contains a synchronized method to apply synchronous behaviour to the program. This method is used to lock an object for shared resources. The object automatically obtained a lock when it invokes the synchronized method and releases when the work is done.

Syntax for Synchronized method:

Example of Java program without the use synchronized method:


Now let see an example with the use synchronized method:


Synchronized block in java:

It is also used to achieve synchronization in java which locks an object for any shared resource. It is the same as a synchronized method.

Using Synchronized block only selected lines of code can be synchronized.

Syntax for Synchronized block:

Example to demonstrate the use of Synchronized block in Java:


Note that:
The scope of the synchronized method is higher than the synchronized block.


Java Program to check Krishnamurthy Number

In this tutorial, we will learn about Krishnamurthy numbers and write a Krishnamurthy Number program in Java. We will write two programs for Krishnamurthy number …
Read More

Java Program for ISBN Number

In this tutorial, we will learn about the ISBN (International Standard Book Number) and write a program to check for the ISBN Number in Java …
Read More

C++ Memory Management

Memory management refers to the process of managing the computer memory while assigning the space to the program’s variable to improve the overall performance. Requirement …
Read More

C++ Pointer to Pointer

As we know by now that a pointer stores the address of the pointed variable. But it is not the only use, pointer also stores …
Read More

C++ Passing Pointers to Functions

A function is a user-defined block of codes that executes some specific task assigned to it invoked by its name. If there is an argument …
Read More

C++ Null Pointer

We use a null pointer when we do not have the exact address to assign to a pointer. It is considered a good practice and …
Read More