How to control access synchronization between static method and instance method

I am learning Threads in Java and I am interested in how to control access synchronization between static and instance methods of a class, since the synchronization of static methods in a class is independent of the synchronization of instance methods on class objects.

At the moment I can not find any situation in real life, so I make an assumption:

Two classes A and B, class A have static methods with a formal parameter of class B, as well as instance methods. Then I create two threads to execute two methods of A.

How many ways to keep state below obj is always consistent?

class B { ... }
class A {
      public synchronized void instanceMethod(B obj){ ... }; 
      public static synchronized void staticMethod(B obj){ ... };

      public static void main(String[] args){
            B obj = new B();
            // create a Thread to modify the state of obj with A instanceMethod
            // create a Thread to modify the state of obj with A staticMethod
      }
}

Thanks for the advanced.

+3
4

A this A, .

. , , , .

. B, , A.

, ?

class B { 
      public synchronized alter() { };
}
class A {
      public void instanceMethod(B obj){ obj.alter(); }; 
      public static void staticMethod(B obj){ obj.alter(); };

      public static void main(String[] args){
            B obj = new B();
            // create a Thread to modify the state of obj with A instanceMethod
            // create a Thread to modify the state of obj with A staticMethod
            obj.alter();
      }
}
+2

"B".

public void instanceMethod(B obj) {
    synchronized(obj) {
        //no other thread will enter a synchronized block on 'obj' since we leave it
        ...
        obj.doSomething();
        ...
        obj.doSomethingElse(); //I can trust here that no other thread manipulated 'obj' since 2 lines before.
        ...
    }
}

.

+2

synchronize a static lock object instead of synchronizing method calls. This gives you additional responsibility for accounting if you want to introduce other methods that synchronize these methods: take a lock for them.

class B { ... }
class A {
      static Object myLock = new Object();
      public void instanceMethod(B obj){ synchronized(myLock) {...} }; 
      public static void staticMethod(B obj){ synchronized(myLock) {...} };

      public static void main(String[] args){
            B obj = new B();
            // create a Thread to modify the state of obj with A instanceMethod
            // create a Thread to modify the state of obj with A staticMethod
      }
}
+1
source

It looks like you are worried about the state of B obj ... Instead of synchronizing the methods of A, use the methods of instance B to internally lock each instance of B. Otherwise, there may be a class C that does not comply with the blocking rules, and you will again fall into an inconsistent state.

0
source

All Articles