In Java, a Synchronized block helps in performing synchronization on any particular resource of the function or method. If there are 100 lines of code(LOC) and synchronization has to be done for only 10 lines, then a synchronized block can be used. Synchronized can be used as keyword, method and blocks. In this tutorial, we will discuss the synchronized block in detail.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
The syntax of the synchronized block is as shown below:
Synchronized( lo) { //statements that have to be synchronized }
Here, lo is the lock object
How does Synchronized Block Work in Java?
As already discussed, the Synchronized block helps in performing synchronization on any particular resource of the function or method. When a thread needs to execute lines that are synchronized inside the synchronized block, it is mandatory to acquire the lock on the monitor of the lock Object lo mentioned in the syntax above. At a time, only 1 thread can acquire the lock object’s monitor. Each thread has to wait until the thread that currently holds the lock completes the execution and releases it.
Similarly, synchronized keyword assures that at a time, only 1 thread will be executing the lines of code in a synchronized block, which in turn prevents more than one thread from corrupting the data which is shared within the block.
Suppose a method consists of500 LOC(lines of code), but there exist only 20 lines of code that holds a critical section(CS) of code. That is, these 20 lines can alter or change the state of the object. So synchronization can be done to these 20 lines of code function to avoid any alteration in object state and make sure that other threads execute the other 480 lines within the particular method without any intermission.
Examples of Synchronized Block in Java
Now, let us see some sample programs on the synchronized block in Java.
Example #1
Java program to implement synchronized block
Code:
class Testsmple{ void printTestsmple(int n) { //start of synchronized block synchronized(this) { System.out.println("The output of synchronized block is: "); for( int i=1 ; i <p><strong>Output:</strong></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500473898450.png?x-oss-process=image/resize,p_40" class="lazy" alt="Synchronized Block in Java" ></p> <p>In this program, two threads t1 and t2, are used where each of them has a method printTestsmple that calls the synchronized method. The thread 1 input for printTestsmple is 10, and the thread 2 input is 200. In the result, it can be seen that the output of the synchronized block of the first thread is 10, 20, 30, 40. At the same time, the result of the thread 2 synchronized block is 200, 400, 600, 800. Moreover, there is a line “The output of the synchronized block is:” which gets printed between each thread’s result.</p> <h4 id="Example">Example #2</h4> <p>Java program to implement synchronized blocks with the help of using anonymous class.</p> <p><strong>Code:</strong></p> <pre class="brush:php;toolbar:false">class Testsmple{ void printTestsmple(int n) { //start of synchronized block synchronized(this) { System.out.println("The output of synchronized block is: "); for( int i=1 ; i <p><strong>Output:</strong></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500474092308.png?x-oss-process=image/resize,p_40" class="lazy" alt="Synchronized Block in Java" ></p> <p>In this program also, two threads t1 and t2, are used where each of them has a method printTestsmple that calls the synchronized method. The thread 1 input for printTestsmple is 10, and the thread 2 input is 200. In the result, it can be seen that the output of the synchronized block of the first thread is 10, 20, 30, 40. At the same time, the result of the thread 2 synchronized block is 200, 400, 600, 800. Moreover, there is a line “The output of the synchronized block is:” which gets printed between each thread’s result. The only difference is the presence of an anonymous class in this program.</p> <h4 id="Example">Example #3</h4> <p>Java program to implement synchronized block.</p> <pre class="brush:php;toolbar:false">import java.util.*; class ABC { String nm = ""; public int cnt = 0; public void samplename(String stringexample, List<string>li) { // In order to change the name at a time, only 1 thread is permitted synchronized(this) { nm = stringexample; cnt++; } li.add(stringexample); } } public class SyncBlockExample { //main method public static void main (String[] args) { //create an object for the class ABC ABC obj = new ABC(); //create a list List<string>li = new ArrayList<string>(); //call the method using the object created obj.samplename("Anna Sam", li); System.out.println(obj.nm); } }</string></string></string>
Output:
In this program, a class ABC is created with a synchronized method inside the method samplename. A string “Anna Sam” is passed as an input for calling the method samplename. On executing the code, the string “Anna Sam” gets printed.
Advantages
Some of the advantages are given below:
- Performance enhancement can be done if the scope of synchronization is limited.
- Synchronize small blocks of code to reduce the computational cost.
- Flexible to use other objects as locks.
- As Java is a multithreaded programming language, it is best to attain mutual exclusion on resources that are shared.
The above is the detailed content of Synchronized Block in Java. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)