Reputation: 3269
Quick question about "best practices" in Java. Suppose you have a database object, with the primary data structure for the database as a map. Further, suppose you wanted to synchronize any getting/setting info for the map. Is it better to synchronize every method that accesses/modifies the map, or do you want to create sync blocks around the map every time it's modified/accessed?
Upvotes: 0
Views: 416
Reputation: 47964
Depends on the scope of your units of work that need to be atomic. If you have a process that performs multiple operations that represent a single change of state, then you want to synchronize that entire process on the Map object. If you are synchronizing each individual operation, multiple threads can still interleave with each other on reads and writes. It would be like using a database cursor in read-uncommitted mode. You might make a decision based on some other threads half-complete work, seeing an incomplete/incorrect data state.
(And of course insert obligatory suggestion to use classes from java.util.concurrent.locks
instead of the synchronized keyword :) )
Upvotes: 2
Reputation: 82559
In the general case, it is better to prefer to synchronize on a private final Object
for non-private methods than it is to have private synchronized
methods. The rationale for this is that you do not want a rouge caller to pass an input to your method and acquire your lock. For private
methods you have complete control over how they can be called.
Personally, I avoid synchronized
methods and encapsulate the method in a synchronized()
block instead. This gives me tighter control and prevents outside sources from stealing my monitor. I cannot think of cases where you would want to provide an outside source access to your monitor, but if you did you could instead pass them your lock object just the same. But like I said, I would avoid that.
Upvotes: 1