How it is possible that both static and non static java synchronized method running in parallel while writing java synchronized code ?
public class Counter{
private static count = 0;
public static synchronized getCount()
{
return this.count;
}
public synchronized setCount(int count)
{
this.count = count;
}
}
Static methods are synchronized on the class object while non static methods are synchronized on the particular instance of the class on which they are invoked. Thus they can execute in parallel since they are generally synchronized on different objects.
In the following example staticMethod1 is essentially the same as staticMethod2 and method1 is the same as method2 only that the latter versions use the object on which they are synchronized explicitly:
class MyClass
{
static synchronized void staticMethod1()
{
doSomething();
}
static void staticMethod2()
{
synchronized( MyClass.class )
{
doSomething();
}
}
synchronized void method1()
{
doSomething();
}
void method2()
{
synchronized( this )
{
doSomething();
}
}
}
I still don't understand the question and I'm confused by your code example. You have static methods referencing "this.counter" yet "counter" is static.
In any event, to re-state some of the other answers, consider:
public static synchronized classMethod() {....}
public synchronized instanceMethod() {...}
"synchronized" means two different things in each case. On classMethod, which is static, "synchronized" applies to the class object's (Counter.class) monitor, while instanceMethod's "synchronized" applies to the object instance's ("this") monitor.
As such, classMethod and instanceMethod will not lock each other. instanceMethod would block another non-static synchronized method, while classMethod would block other static synchronized methods.
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