Disclaimer: This code is copied from synchronized blocks for static and non-static methods
I made some modification to it. I want to know how to make threads call both synchronized static and non-static methods. I can make it work by wrapping the non-static method in a synchronized block. Is there any other way?
public class StaticNonStaticSynch
{
public static void main(String[] args)
{
final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest();
Runnable runnable1 = new Runnable()
{
@Override
public void run()
{
staticNonStaticTest.nonStaticMethod();
}
};
Runnable runnable2 = new Runnable()
{
@Override
public void run()
{
StaticNonStaticTest.staticMethod();
}
};
Thread thread1 = new Thread(runnable1, "First Thread");
Thread thread2 = new Thread(runnable2, "Second Thread");
thread1.start();
thread2.start();
}
}
class StaticNonStaticTest
{
void nonStaticMethod()
{
//synchronized (StaticNonStaticTest.class){
for(int i=0;i<50;i++)
{
System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
// }
}
static synchronized void staticMethod()
{
for(int i=0;i<50;i++)
{
System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
}
}
Remember that this:
Essentially compiles to this:
Notice that they don’t synchronize on the same thing. To fix this, create an object for both of them to lock on (known as a mutually exclusive object, or a “mutex”):
That should make it so that only one of these two methods are running at the same time across multiple threads.
A couple tips:
synchronized(variable)on avariablethat’sfinal.MUTEXdoesn’t have to be strictly a mutex, it could be an actual object. See the example below.synchronizedmodifier on methods is effectively implemented. It’s just like asynchronizedblock onthisorMyClass.class.Besides having an object that’s strictly a mutex, you can use any field that’s
final. For example, to synchronize on aMapduring iteration:This code guarantees that you’ll never get a
ConcurrentModificationException