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.
No. A
synchronizedmethod in Java is identical to the whole method having its body wrapped in asynchronized (this)block. So if one thread is in asynchronizedmethod, another thread cannot simultaneously be in a differentsynchronizedmethod on the same object.The way this relates to a
Vectoris 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.