0

What is the difference between synchronizing an object and synchronizing the instance? And what is more efficient?

synchronize(this) {
// things to synchronize 
}

Or

private static final Object LOCK = new Object();

synchronize(LOCK) {
// things to synchronize 
}
Fabian
  • 650
  • 2
  • 9
  • 21
  • In one case you're locking on `this` (the current instance), and in the other case you're locking on `LOCK`. Could you be more specific about what you're confused about? – Mark Rotteveel Apr 11 '18 at 09:54
  • Plenty of duplicates and literature in SO, let alone elsewhere. – Mena Apr 11 '18 at 09:55
  • I‘m confused about what to use, because I can lock the object or lock the instance and both do the same. But is it more efficient only locking the object or the instance because of the ressources used? – Fabian Apr 11 '18 at 09:59
  • 1
    Synchronization with private (non pooled) object is ideally better then synchronizing on `this`. As object referenced by `this` is usually present in some outside class and there may be various references which also can be shared between multiple classes. If unintentionally some developer (or same developer by mistake unintentionally) uses the shared reference for synchronization for some outer code which is for some other concern then this may lead to dead locks. This is the same reason why even pooled String objects should not be used as lock for synchronization. – nits.kk Apr 11 '18 at 10:38

0 Answers0