Synchronize two methods in different classes (and different packages)

前端 未结 1 1246
长发绾君心
长发绾君心 2021-01-06 18:04

I\'m facing an issue regarding Java method synchronization. Let\'s hope I can explain it briefly:

I have two different methods in two different classes, in two diffe

相关标签:
1条回答
  • 2021-01-06 18:59

    Both of your approaches should work, but I don't think locking on class is a recommended practices. Prefer locking on instances of Object, or use proper locks from java.util. Also, do not lock on String.

    Alternatively, you could let instances of classes Class1 and Class2 can take a lock as parameter during instantiation:

       class Class1 {
            private final Object lock;
            public Class1( Object lock ) { this.lock = lock }
            public method() { synchronize( lock ) { } );
       }
    

    Then make sure that you create one lock (with new Object()) and pass it to the two instances of Class1 and Class2.

    So basically, you've broken down the original problem in two: 1) the two classes do no share anything statically global, they just receive a parameter. 2) the clients of Class1 and Class2 must pass the correct lock. The client of Class1 and Class2 acts as the "orchestrator".

    0 讨论(0)
提交回复
热议问题