Imagine a class that is built on revolve around the state of a single private object variable (lets say a Map<Something>), where all methods in this class are either getting, setting or otherwise modifying that object.
Which of the two synchronization approaches is better in your mind? Perhaps there exists a 3rd, better option.
- Make all methods in the class that encapsulates the object synchronized, or synchronize on the object being modified
- Make all methods that access then instance of the class that encapsulates the object synchronized.
In other words, is it better to synchronize from inside or outside?
Those methods that have access to the
Map variableshould contain asynchronized(variable) { }block, and all access to that variable must be in that block. Thevariablemust not be null, of course.This way you can handle the time better what your code spends in the protected block (e.g. read or write access to the
variable).Other aspect: if your Class have more than one resource to protect, you cannot do the same, because they will interfere with each other.