My doubt is do we need to make static methods as synchronized if it is called within synchonized non static method?
for e.g.
class Test
{
public static void m2()
{
}
public synchronized void m1()
{
Test.m2();
----
----
}
In above case do I need to make m2 as synchronized in order to avoid race condition or should I keep it as it is.
}
Static Synchronized method is also a method of synchronizing a method in java such that no two threads can act simultaneously static upon the synchronized method. The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.
static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.
A synchronized block of code can only be executed by one thread at a time. Synchronization in Java is basically an implementation of monitors . When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method , the monitor belongs to the class.
When a thread calls a synchronized method, it acquires the intrinsic lock. After the thread finishes executing the method, it releases the lock, which allows other threads to acquire the lock and get access to the method.
It depends on what your static method is doing. Do you really need it to be synchronized at all? Is it accessing shared mutable state?
If so, you probably do need to synchronize (although I wouldn't do so just with the synchronized
modifier - I'd create a private static final variable with an object to lock on.)
The fact that your instance method is synchronized means that no two threads will be executing it with the same target object - but two threads could both be executing m1
with different target objects, so m2
could be called twice at the same time. Whether that's a problem or not depends on what it's doing. If it's not using any shared state (e.g. it's really just computing something based on its parameters) then it doesn't need to be synchronized at all.
Generally speaking, it's more important for static methods to be thread-safe than instance methods: I typically don't make types themselves thread-safe, but instead try to use a few classes to manage concurrency, with each thread using its own set of separate objects as far as possible.
You do need to make m2
synchronized. Otherwise someone can call that method at the same time. I am assuming m2
would be considered for being synchronized, otherwise it is a moot point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With