Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two different synchronized methods of the same object?

I have 2 synchronized methods in a class say method1() and method2(). A thread say "Thread 1" holds the lock on that object of the class by executing the synchronized method1().Can another thread say "Thread 2" , access the lock via method2() at the same time while "Thread 1" holding the lock.

This case is analogs to java.util.Vector class having synchronized add() and remove() methods. Please explain this case too.

like image 892
JavaUser Avatar asked Jul 12 '10 07:07

JavaUser


People also ask

What are the two Synchronisation methods?

There are two types of thread synchronization mutual exclusive and inter-thread communication. Synchronized method. Synchronized block.

Can different synchronized instance methods execute at same time?

Indeed, it is not possible! Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously. Save this answer.

Can two threads access two different synchronized methods of a single class at the same time?

So can two threads access a synchronized method at the same time? Yes, if the method is called on different instances of the class.

What will happen if synchronized method is called by two threads on different object instances simultaneously?

Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.


2 Answers

No. A synchronized method in Java is identical to the whole method having its body wrapped in a synchronized (this) block. So if one thread is in a synchronized method, another thread cannot simultaneously be in a different synchronized method on the same object.

The way this relates to a Vector is that you don't want some code trying to remove an element while other code is trying to add an element. This is the concept of a critical section; you not only don't want someone else trying to do what you're doing, you also don't want someone else doing something different that would interfere.

like image 54
Borealid Avatar answered Sep 18 '22 18:09

Borealid


Thread2 can access the lock but can't enter the block guarded by that lock as long as Thread1 is holding the same lock.

like image 27
whiskeysierra Avatar answered Sep 21 '22 18:09

whiskeysierra