Kingamere Kingamere - 2 months ago 20
Java Question

Java acquire monitor lock of other class

Let's say I have this class:

public class Status {
private int x;

// monitor lock?
public Object myLock = new Object();

public Status(int x) {
this.x = x;
}

public int checkVar() {
return x;
}

public int incrementVar() {
++x;
}
}


Then I have a thread class like this:

public class MyThread implements Runnable {

public void run() {
// Is this how to acquire monitor lock of Status class?
synchronized (statusInstance.myLock) {
statusInstance.checkVar();
statusInstance.incrementVar();
}
}
}


This is how you acquire the monitor lock of another class right?

Answer

In Java if you have a reference to any object you can use it as a mutex. But you would be locking on the object and not the class.

The problem is that anyone can mutate that object because it is public and obtain a lock they shouldn't be acquiring.

 statusInstance.myLock = new Object();

Using public mutable objects as mutexes is considered harmful. You can lock on the class given there is only one class in the ClassLoader

 synchronized(Status.class){
    ..
 }

Or making your lock static final

public static final Object MY_LOCK = new Object();    
Comments