The second method (locking on objects) is preferable, since it gives you more control when locking. Moreover, this prevents the outside of your class from blocking your class indefinitely, preventing the execution of its own methods.
Consider the following: Imagine that some external code contains the following statements:
synchronized (Foo.class) { Thread.sleep(10000); }
Now, if you used synchronization in the methods of the class itself, as in method 1, other classes that are simultaneously trying to call method A or methodB will be blocked until the sleep ends. If, however, you used internal locking of internal objects, as in method 2, then other classes do not have to wait.
Due to the above, I would not recommend method 1.
PS I just noticed that the internal locks in method 2 were not declared final. This will be a problem if they are reassigned when the method is busy locking on them (the lock will then be on another instance). To prevent this, rather declare them final, as shown below:
final static Resource resource1 = new Resource(...); final static Resource resource2 = new Resource(...);
In short, never sync with non-final objects.
source share