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.
}
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
synchronizedmodifier – 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
m1with different target objects, som2could 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.