Radi Hadzhiyski wrote:That's true, I was in a hurry and forgot to mention, that no side code should be considered (assumed multiple threads will just call the doIt() and the resources modified within doIt() are not modified elsewhere)
Then it should be fine. In theory you could still have problems if multiple classloaders load that Bar class, and the sync block operates on data shared across those classloaders, as they'll have distinct Bar.class objects. That's scenario seems very unlikely in general though.
Jeff Verdegan wrote:In general, though, syncing on the Class object for a different class is quite unusual (I don't think I've ever seen it, in 15 years of Java programming), and it's probably a red-flag for your design.
Exactly, that's my point too I am actually pretty familiar with multi-threading, but I as I saw this for the first time in my life , I was very curious, whether I don't miss something.
Ah, so you inherited that code? Yeah, that's always fun, wondering whether the guy before us knew something we don't know, and had a good reason for doing things that way, or if he just screwed up.
There are a couple of scenarios where I could imagine someone doing that, but even in those scenarios, I'd probably do it differently.
1. Foo is a nested class of bar. You might get multiple different Foo instances, nested in multiple different Bar objects, and you want all their doIt's to sync on the same object. Bar.class is an easy common object to grab. I'd probably use Foo.class though, or a prrivate static final Object member variable in Foo.
2. Bar itself has some static methods that need to share the same lock as Foo.doIt().
If neither of those situations apply, then I don't have another guess as to what the original coder might have been thinking.