views:

19

answers:

2

I have a manager as Spring wired bean. I believe every bean defined for spring by default is wired as singleton. I have some methods in this bean which I need to synchronize. How should I be doing that then --

void zzz() {
 synchronized (this) {
   ...
 }
}

or

void zzz() {
 synchronized (MyClass.class) {
   ...
 }
}

?

+1  A: 

Unless you're accessing mutable static class variables (potentially nasty to begin with), the first is the appropriate way to synchronize.

Understand that while Spring is only creating one instance of a singleton bean and using it for anybody who has a dependency on a bean of that type, the singleton is not a static entity. There is no compiler constraint preventing you from instantiating that class yourself outside the Spring context. It's simply the only instance because Spring knows not to make more of them... not because it can't be done. The point I'm trying to make here is that it's iffy bordering on incorrect to draw a parallel between class-level data and the singleton's data.

In corollary, synchronization should occur on the narrowest scope possible. In your case, that means synchronize on the object instance containing the shared data rather than on the wider scope of the entire class.

RonU
A: 

The main difference in the two is that in the first case, the the instance of the class as the monitor and the second one uses the Class as the monitor.

The first one is probably the way to go in your case because, in the near future if you decide to have many instances of your class, their methods will be synchronized on the respective instances. As opposed to if you use a Class as a monitor, if one thread is calling a synchronized method on one instance, no other threads will be able to call methods (those that are synchronized) on any instances of the same class.

naikus