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.


C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a number using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …