How to synchronize or lock upon variables in Java?
That's pretty easy:
class Sample {
private String message = null;
private final Object lock = new Object();
public void newMessage(String x) {
synchronized (lock) {
message = x;
}
}
public String getMessage() {
synchronized (lock) {
String temp = message;
message = null;
return temp;
}
}
}
Note that I didn't either make the methods themselves synchronized or synchronize on this
. I firmly believe that it's a good idea to only acquire locks on objects which only your code has access to, unless you're deliberately exposing the lock. It makes it a lot easier to reassure yourself that nothing else is going to acquire locks in a different order to your code, etc.
From Java 1.5 it's always a good Idea to consider java.util.concurrent package. They are the state of the art locking mechanism in java right now. The synchronize mechanism is more heavyweight that the java.util.concurrent classes.
The example would look something like this:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sample {
private final Lock lock = new ReentrantLock();
private String message = null;
public void newmsg(String msg) {
lock.lock();
try {
message = msg;
} finally {
lock.unlock();
}
}
public String getmsg() {
lock.lock();
try {
String temp = message;
message = null;
return temp;
} finally {
lock.unlock();
}
}
}
For this functionality you are better off not using a lock at all. Try an AtomicReference.
public class Sample {
private final AtomicReference<String> msg = new AtomicReference<String>();
public void setMsg(String x) {
msg.set(x);
}
public String getMsg() {
return msg.getAndSet(null);
}
}
No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.