Java Multi threading

Synchronized block in Java Multithreading

Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 100 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.
 
Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Points to remember for Synchronized block

  1. Synchronized block is used to lock an object for any shared resource.
  2. Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

synchronized (object reference expression) { 
   //code block 
 }

Example of synchronized block:
Let’s see the simple example of synchronized block.

class First
{
   public synchronized void display(String msg) 
   {
      System.out.print ("["+msg);
      try
      {
         Thread.sleep(500); 
      }
      catch(InterruptedException e)
      {
         e.printStackTrace();
      }
      System.out.println ("]");
   }
}

class Second extends Thread
{
     String msg;
     First fobj;
     Second (First fp,String str)
     {
        fobj = fp;
        msg = str;
        start();
     }
     public void run()
     {   
        synchronized(fobj){         //synchronized block
            fobj.display(msg);
         }
     }
}

public class SyncBlockDemo
{
    public static void main (String[] args) 
    {
       First fnew = new First();
       Second ss  = new Second(fnew, "welcome");
       Second ss1 = new Second (fnew,"to");
       Second ss2 = new Second(fnew, "dineshonjava.com");
    }
}

output:

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago