Java synchronized block

We have read synchronization in java and method synchronization with synchronized keyword. In method synchronization, we synchronized the whole code of method. But sometimes we want to synchronize a portion of a method, not the whole method. For such types of situations, we should use Java synchronized block. In this post, we will read it in detail.

Here is the table content of the article will we will cover this topic.
1. Java synchronized block
i) synchronized block in non-static method
ii) synchronized block in static method

Java synchronized block

Java synchronized block

The Java synchronized block is used to synchronize a portion of code or set of the statement. Like the synchronized method, synchronized blocks in Java are marked with the synchronized keyword. A synchronized block can be executed by only one thread at a time and all other threads wait for the completion of execution.

synchronized ( lockObject)
{
       //synchronized statements
}

A thread can execute the synchronized block only to acquire the lock on lockObject. Only one thread can acquire the monitor of a lock object at a time meanwhile all other threads wait for the lock.  

We can have two type of synchronized block.

1. synchronized block in non-static method

When you want to synchronize a portion of the method instead of the whole method. We can use a synchronized block of Java code inside an unsynchronized Java method.

access_modifiers return_type method_name(method_parameters)
{ 
       synchronized (objLock) 
       {
             // block of code
        }
        // method_code 
}

You must think about why the synchronized block construct takes an object in parentheses. This object is known as the monitor object. Only one thread can execute inside a Java code block synchronized on the same monitor object.

class Test 
{ 
    public void countIncrement() 
    { 
    	synchronized(this)
    	{
	        for (int i = 0; i < 3; i++) 
	        { 
	            System.out.println(i); 
	            try 
	            { 
	                Thread.sleep(400); 
	            } 
	            catch (Exception e) 
	            { 
	                System.out.println(e); 
	            } 
	        } 
    	}
    } 
} 
  
class MyThread extends Thread { 
   
    Test test; 
  
    MyThread (Test test) { 
        this.test = test; 
    } 
  
    @Override
    public void run() { 
        test.countIncrement(); 
    } 
} 
  
public class SynchronizedMethod 
{ 
    public static void main(String[] args) 
    { 
        Test obj = new Test(); 
  
        MyThread thread1 = new MyThread(obj); 
        MyThread thread2 = new MyThread(obj); 
  
        thread1.start(); 
        thread2.start(); 
    } 
} 

Output: 0
1
2
0
1
2

2. synchronized block in static method

We can use the Synchronized blocks inside the static method. Suppose of we have two static methods with a synchronized block then only one thread can execute inside any of these two methods at the same time.

class Test 
{ 
    synchronized static public void countIncrement() 
    { 
    	synchronized (Test.class) 
    	{
    		System.out.println("Increment values");
            for (int i = 0; i < 3; i++) 
            { 
                System.out.println(i); 
                try 
                { 
                    Thread.sleep(400); 
                } 
                catch (Exception e) 
                { 
                    System.out.println(e); 
                } 
            } 
		}
    	
    } 
    synchronized static public void countDecrement() 
    { 
    	synchronized (Test.class) 
    	{
	    	System.out.println("Decrement values");
	        for (int i = 3; i > 0; i--) 
	        { 
	            System.out.println(i); 
	            try 
	            { 
	                Thread.sleep(400); 
	            } 
	            catch (Exception e) 
	            { 
	                System.out.println(e); 
	            } 
	        } 
    	}
    } 
} 
  
class MyThread extends Thread { 
   
    Test test; 
  
    MyThread (Test test) { 
        this.test = test; 
    } 
  
    @Override
    public void run() { 
        test.countIncrement(); 
        test.countDecrement();
    } 
} 
  
public class SynchronizedMethod 
{ 
    public static void main(String[] args) 
    { 
        Test obj = new Test(); //Object of Apple class that is shared amoung threads
  
        MyThread thread1 = new MyThread(obj); 
        MyThread thread2 = new MyThread(obj); 
  
        thread1.start(); 
        thread2.start(); 
    } 
} 

Output: Increment values
0
1
2
Increment values
0
1
2
Decrement values
3
2
1
Decrement values
3
2
1

1 thought on “Java synchronized block”

  1. Dear friend. I truly just like your posting and your current web page all in all! That write-up is really plainly composed and without difficulty understandable. Your WordPress style is awesome as well! Would be awesome to discover exactly where My partner and i are able obtain this. Please hold up the very good work. We all need much more this kind of website owners just like you on the web and much less spammers. Wonderful man!

    Reply

Leave a Comment