简体   繁体   中英

Resource shared between static and non-static methods in java

I know that static synchronized method locked on class object and while instance synchronized method locks on current instance of Object ie this .

Since both of these object are different they have different lock so while one thread is executing static synchronized method , other thread in java doesn't need to wait for that thread to return instead it will acquire separate lock.

Consider following example

public class Test {
  static int count = 0;

  public synchronized void f1(){
    count++;
  }

  public static synchronized void f2(){
    count++;
  }
}

here shared count is not accessed in mutual exclusive fashion which may result in passing incorrect count to caller of f1() while another thread is incrementing count using static f2() method.

What is solution over this situation? Am i am asking correct question if not please make me correct? And if it is a true situation then what solution does java pr ovoids?

You can use synchronized block on the non-static method and it should use the same monitor as the static synchronized method:

public void f1() {
   synchronized(Test.class) {
     count++;
   }
}

The rule of thumb is that static synchronized methods should be used to protect only static variables, while non-static synchronized methods should be used to protect only non-static variables.

Since count is static, modifying it from a block with non-static synchronization is incorrect. To code this correctly, and also to avoid code duplication, call f2 from f1 , like this:

public void f1(){
    ... // Do something ...
    f2();
    ... // Do something else ...
}

public static synchronized void f2(){
    count++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM