Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Synchronization in java

Tags:

java

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;
   }
}
like image 505
PENNY Avatar asked Jul 05 '26 07:07

PENNY


2 Answers

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();
        }
    }
}
like image 107
x4u Avatar answered Jul 06 '26 20:07

x4u


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.

like image 26
wrschneider Avatar answered Jul 06 '26 20:07

wrschneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!