If I synchronized two methods on the same class, can they run simultaneously?

JavaMultithreadingSynchronizedJava Threads

Java Problem Overview


If I synchronized two methods on the same class, can they run simultaneously on the same object? For example:

class A {
	public synchronized void methodA() {
		//method A
	}

	public synchronized void methodB() {
		// method B
	}
}

I know that I can't run methodA() twice on same object in two different threads. same thing in methodB().

But can I run methodB() on different thread while methodA() is still running? (same object)

Java Solutions


Solution 1 - Java

Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).

Solution 2 - Java

In the example methodA and methodB are instance methods (as opposed to static methods). Putting synchronized on an instance method means that the thread has to acquire the lock (the "intrinsic lock") on the object instance that the method is called on before the thread can start executing any code in that method.

If you have two different instance methods marked synchronized and different threads are calling those methods concurrently on the same object, those threads will be contending for the same lock. Once one thread gets the lock all other threads are shut out of all synchronized instance methods on that object.

In order for the two methods to run concurrently they would have to use different locks, like this:

class A {
    private final Object lockA = new Object();
    private final Object lockB = new Object();

    public void methodA() {
        synchronized(lockA) {
            //method A
        }
    }

    public void methodB() {
        synchronized(lockB) {
            //method B
        }
    }
}

where the synchronized block syntax allows specifying a specific object that the executing thread needs to acquire the intrinsic lock on in order to enter the block.

The important thing to understand is that even though we are putting a "synchronized" keyword on individual methods, the core concept is the intrinsic lock behind the scenes.

Here is how the Java tutorial describes the relationship:

> Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility. > > Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

The purpose of locking is to protect shared data. You would use separate locks as shown in the example code above only if each lock protected different data members.

Solution 3 - Java

Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.

In your case, the methods(instance) are of same class. So when ever a thread enters into java synchronized method or block it acquires a lock(the object on which the method is called). So other method cannot be called at the same time on the same object until the first method is completed and lock(on object) is released.

Solution 4 - Java

In your case you synchronized two method on the same instance of class. So, these two methods can't run simultaneously on different thread of the same instance of class A. But they can on different class A instances.

class A {
    public synchronized void methodA() {
        //method A
    }
}

is the same as:

class A {
    public void methodA() {
        synchronized(this){
            // code of method A
        }
    }
}

Solution 5 - Java

Think of your code as the below one:

class A {

public void methodA() {
    synchronized(this){        
      //method A body
    }
}

public void methodB() {
    synchronized(this){
      // method B body
    }
}

So, synchronized on method level simply means synchronized(this). if any thread runs a method of this class, it would obtain the lock before starting the execution and hold it until the execution of the method is finished.

> But can I run methodB() on different thread while methodA() is still > running? (same object)

Indeed, it is not possible!

Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.

Solution 6 - Java

From oracle documentation link

Making methods synchronized has two effects:

> First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. > >Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

This will answer your question: On same object, You can't call second synchronized method when first synchronized method execution is in progress.

Have a look at this documentation page to understand intrinsic locks and lock behavior.

Solution 7 - Java

Just to all clarity, It’s possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because one is having object level lock and other class level lock.

Solution 8 - Java

The key idea with synchronizing which does not sink in easily is that it will have effect only if methods are called on the same object instance - it has already been highlighted in the answers and comments -

Below sample program is to clearly pinpoint the same -

public class Test {

public synchronized void methodA(String currentObjectName) throws InterruptedException {
	System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA in");
	Thread.sleep(1000);
	System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA out");
}

public synchronized void methodB(String currentObjectName)  throws InterruptedException {
	System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB in");
	Thread.sleep(1000);
	System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB out");
}

public static void main(String[] args){
	Test object1 = new Test();
	Test object2 = new Test();
	//passing object instances to the runnable to make calls later
	TestRunner runner = new TestRunner(object1,object2);
	// you need to start atleast two threads to properly see the behaviour
	Thread thread1 = new Thread(runner);
	thread1.start();
	Thread thread2 = new Thread(runner);
	thread2.start();
}
}

class TestRunner implements Runnable {
Test object1;
Test object2;

public TestRunner(Test h1,Test h2) {
	this.object1 = h1;
	this.object2 = h2;
}

@Override
public void run() {
	synchronizedEffectiveAsMethodsCalledOnSameObject(object1);
	//noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(object1,object2);
}

// this method calls the method A and B with same object instance object1 hence simultaneous NOT possible
private void synchronizedEffectiveAsMethodsCalledOnSameObject(Test object1) {
	try {
		object1.methodA("object1");
		object1.methodB("object1");
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

// this method calls the method A and B with different object instances object1 and object2 hence simultaneous IS possible
private void noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(Test object1,Test object2) {
	try {
		object1.methodA("object1");
		object2.methodB("object2");
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
}

Notice the difference in output of how simultaneous access is allowed as expected if methods are called on different object instances.

Ouput with noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects() commented -the output is in order methodA in > methodA Out .. methodB in > methodB Out Ouput with noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects() commented

and Ouput with synchronizedEffectiveAsMethodsCalledOnSameObject() commented - the output shows simultaneous access of methodA by Thread1 and Thread0 in highlighted section -

Ouput with synchronizedEffectiveAsMethodsCalledOnSameObject() commented

Increasing the number of threads will make it even more noticeable.

Solution 9 - Java

No it is not possible, if it were possible then both method could be updating same variable simultaneously which could easily corrupt the data.

Solution 10 - Java

You are synchronizing it on object not on class. So they cant run simultaneously on the same object

Solution 11 - Java

Two different Threads executing a common synchronized method on the single object, since the object is same, when one thread uses it with synchronized method, it will have to verify the lock, if the lock is enabled, this thread will go to wait state, if lock is disabled then it can access the object, while it will access it will enable the lock and will release the lock only when it's execution is complete. when the another threads arrives, it will verify the lock, since it is enabled it will wait till the first thread completes his execution and releases the lock put on the object, once the lock is released the second thread will gain access to the object and it will enable the lock until it's execution. so the execution will not be not concurrent, both threads will execute one by one, when both the threads use the synchronized method on different objects, they will run concurrently.

Solution 12 - Java

Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock. So if you want to run simultaneously, create two objects and then try to run by using of those object reference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShelefView Question on Stackoverflow
Solution 1 - JavaNPEView Answer on Stackoverflow
Solution 2 - Javaпутин некультурная свиньяView Answer on Stackoverflow
Solution 3 - JavaSrikanthView Answer on Stackoverflow
Solution 4 - JavaOleksandr_DJView Answer on Stackoverflow
Solution 5 - JavaKhosro MakariView Answer on Stackoverflow
Solution 6 - JavaAditya WView Answer on Stackoverflow
Solution 7 - JavapacmanfordinnerView Answer on Stackoverflow
Solution 8 - JavasomshivamView Answer on Stackoverflow
Solution 9 - JavafastcodejavaView Answer on Stackoverflow
Solution 10 - JavaAjinkyaView Answer on Stackoverflow
Solution 11 - JavaAnkit yadavView Answer on Stackoverflow
Solution 12 - JavacooltsView Answer on Stackoverflow