The Java documentation says that “it is not possible for two invocations of synchronized methods on the same object to interleave”. What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.
E.g. class Worker has method called process(). We have several instances of Worker running in their own threads. We want to prevent more than one instance running the process() method simultaneously. Will synchronized do this?
Thanks.
No;
synchronizedonly prevents multiple threads from simultaneously executing the method in the same instance. If you have n instances, there could be n threads, each executing the method in one of the instances.If you need to ensure that only one thread may execute the method across all instances, you should make the method
static, or make the method non-synchronizedand rather use asynchronizedblock inside the method to lock on aprivate staticfield.Edit: Note that synchronizing on a
privateinstance variable is preferrable to having asynchronizedmethod or to synchronize onthis, and that locking on aprivate staticinstance variable is preferrable to having astatic synchronizedmethod or an instance method that synchronizes onthis.getClass(). The reason is thatthisandthis.getClass()are object references that are accessible throughout the program, so anybody may synchronize on these objects, and thereby block threads that want to call your method.Edit: Also, see @Cowan’s comment below – summary: if you really want to lock on the class, you might want to use
synchronized (Worker.class)rather thansynchronized (this.getClass()), depending on what effect you want in the case of subclassing.