Let me use this small and simple sample:
class Sample {
private String msg = null;
public void newmsg(String x){
msg = x;
}
public String getmsg(){
String temp = msg;
msg = null;
return temp;
}
}
Let's assume the function newmsg()
is called by other threads that I don't have access to.
I want to use the synchonize method to guarantee that the string msg
is only used by one function per time. In other words, function newmsg()
cannot run at the same time as getmsg()
.
Use the
synchronized
keyword.Using the
synchronized
keyword on the methods will require threads to obtain a lock on the instance ofsample
. Thus, if any one thread is innewmsg()
, no other thread will be able to get a lock on the instance ofsample
, even if it were trying to invokegetmsg()
.On the other hand, using
synchronized
methods can become a bottleneck if your methods perform long-running operations - all threads, even if they want to invoke other methods in that object that could be interleaved, will still have to wait.IMO, in your simple example, it's ok to use synchronized methods since you actually have two methods that should not be interleaved. However, under different circumstances, it might make more sense to have a lock object to synchronize on, as shown in Joh Skeet's answer.
If on another occasion you're synchronising a Collection rather than a String, perhaps you're be iterating over the collection and are worried about it mutating, Java 5 offers:
CopyOnWriteArrayList
CopyOnWriteArraySet
For this functionality you are better off not using a lock at all. Try an AtomicReference.
No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.
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:
In this simple example you can just put
synchronized
as a modifier afterpublic
in both method signatures.More complex scenarios require other stuff.
That's pretty easy:
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.