The static synchronized methods of the same class always block each other as only one lock per class
abhi chakraborty
Greenhorn
Joined: Feb 08, 2010
Posts: 2
posted
0
I came across these statements
=> The static synchronized methods of the same class always block each
other as only one lock per class exists. So no two static synchronized
methods can execute at the same time.
=> When a synchronized non static method is called a lock is obtained on
the object. When a synchronized static method is called a lock is obtained
on the class and not on the object.
I wrote these simple programs to understand how exactly it works.
1. TestStaticSync.testSync1() - Obtains lock for all static synchronized methods of class TestStaticSync. TestStaticSync.testSync2() will be waiting for this lock to be released.
2. testStaticSync.nonStaticMethod1(); - Obtains lock for all instance methods which are invoked using the object reference testStaticSync.
3. TestStaticSync.testSync2() - As no Class level lock is present for static synchronized methods testSync2 obtains the class level lock.
4. testStaticSync.nonStaticMethod2(); - As object lock is released by nonStaticMethod1, nonStaticMethod2 obtains the lock.
Kuldip
abhi chakraborty
Greenhorn
Joined: Feb 08, 2010
Posts: 2
posted
0
In that case if both the threads try to access TestStaticSync.testSync1() , Then the static synchronized methods of the same class should block each other as only one lock per class.
public class ThreadOne implements Runnable
{
TestStaticSync testStaticSync;
ThreadOne(TestStaticSync t)
{
this.testStaticSync = t;
new Thread(this,"ThreadOne").start();
}
public void run()
{
TestStaticSync.testSync1(); testStaticSync.nonStaticMethod1();
}
}
public class ThreadTwo implements Runnable
{
TestStaticSync testStaticSync;
ThreadTwo(TestStaticSync t)
{
this.testStaticSync = t;
new Thread(this,"ThreadTwo").start();
}
public void run()
{
TestStaticSync.testSync1(); testStaticSync.nonStaticMethod2();
}
}
But, in that case also I'm getting the same output.
1. TestStaticSync.testSync1() - Class level lock is obtained for all static synchronized methods and the second thread is waiting for the Class lock to be released to invoke TestStaticSync.testSync1(). Hence program output for synchronized methods are shown below