Java synchronized method

We have read synchronization in java and Java block synchronization. Multiple threads used the shared resources and access the fields and objects reference fields. But it can create a problem in data inconsistency or thread interference. We prevent these errors by use of synchronized keyword in java.  Lets read the Java synchronized method.

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

Java synchronized method

Java synchronized method

To achieve the synchronization in java we can use the java synchronized keyword with the method. A synchronized method is used to ensure that only one thread can execute it at a time. As we discussed each object has a lock or monitor, so when any thread accesses it, the thread performs certain operations:   

1. A thread checks the lock of synchronized method. If there no other thread is executing it then lock will be available.

2. If the lock is available, the thread takes the lock and performs the operation as per requirements. Meanwhile, all the other thread waits for the lock.

3. Multiple threads can’t take lock at same time.

The synchronized keyword can be used with a static method and a non-static method(instance methods). Here we will see the static and non-static synchronized method in java.

1. Java synchronization with non-static method

A synchronized non-static method is synchronized on the object level. If the method is non-static, the lock is acquired on the current object. Each object has its synchronized methods and only one thread per object can execute inside a synchronized method.  It is also known as object level locking.

Syntax of synchronized Method

access_modifiers synchronized return_type method_name(method_parameters)
{ 
     // method_code 
}

Let’s see thread synchronization in java simple example

class Test 
{ 
    synchronized public void count() 
    { 
        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.count(); 
    } 
} 
  
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: 0
1
2
0
1
2

In the above example, we are creating two threads thread1 and thread2. Both are using the synchronized count()  method. As it is synchronized, both are using it one by one. Firstly,  thread1 enters the count() method and gets a lock meanwhile thread2 waits until thread1 finishes the execution. and release the lock. After that thread2 gets the lock and completes the execution.

2. Java synchronized static method

As we know static methods belong to a class instead of an object. When we use a synchronized keyword with a static method, the lock is acquired in the class. In synchronized static methods only one thread can execute inside a static synchronized method in the same class. If we have more than one static synchronized method, then only one thread can execute any of these methods at the same time.
Suppose we have two static synchronized methods, method1 and method2 and two threads thread1 and thread2. Here thread1 or thread2 can execute only one static method.

Syntax of static synchronized Method

access_modifiers synchronized static return_type method_name(method_parameters)
{ 
    // method_code 
}
class Test 
{ 
    synchronized static public void countIncrement() 
    { 
    	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() 
    { 
    	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

In above example, we have two static synchronized method (countIncrement() method and countDecrement() method) and two threads(thread1 and thread2). One thread can access only one static method at a time.

2 thoughts on “Java synchronized method”

  1. I’m often to blogging and i in actuality respect your content. The piece of writing has actually peaks my interest. I’m going to bookmark your post and preserve checking for brand new information.

    Reply
  2. I admire the valuable information and facts you provide inside your articles. I will bookmark your weblog and also have my youngsters examine up here often. Im very sure they will learn a lot of new things here than anyone else!

    Reply

Leave a Comment