I have a question regarding Java concurrency. If I synchronize a critical section based on an object, what is difference between declaring that variable as a final static Object
versus simply final Object
.
I understand that the static
keyword defines a variable as belonging to the class, but I'm a little hazy on its meaning in a multi-threaded environment.
Please refer to the code sample below. Currently I have the lock
object declared as private final Object lock = new Object()
, what will be the difference if I add the static
keyword?
class ConcurrencySample {
private String message = null;
private final Object lock = new Object();
//private final static Object lock = new Object();
public void setMessage(String msg) {
synchronized (lock) {
message = msg;
}
}
public String getMessage() {
synchronized (lock) {
String temp = message;
message = null;
return temp;
}
}
}
Thanks for the help!