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 different packages. Something like:
Package1
|_Class1
\MethodA
Package2
|_Class2
\MethodB
Ok, so now I need to synchronize these two methods, which are not threads. So far, I have two different approaches:
Shared semaphore.
Create a shared static semaphore outside Package1
and Package2
, something like:
package Package3;
public class SemaphoreClass {
public static Semaphore;
}
I don't really know if JVM would consider this a shared semaphore, anyway.
Synchronized (SharedClass.class).
Using a shared class to synchronize those two methods, something like:
public void MethodA() {
synchronized (SharedClass.class) {
//...
}
and
public void MethodB() {
synchronized (SharedClass.class) {
//...
}
Anyway, these are just approaches. I would like to hear what's the best way to implement what I'm trying to achieve. Having a shared semaphore for JVM would make things easier, but well, I know there must be a solution for this. Thanks in advance.
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 fromjava.util
. Also, do not lock onString
.Alternatively, you could let instances of classes
Class1
andClass2
can take a lock as parameter during instantiation:Then make sure that you create one lock (with
new Object()
) and pass it to the two instances ofClass1
andClass2
.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
andClass2
must pass the correct lock. The client ofClass1
andClass2
acts as the "orchestrator".