These are both using intrinsic locks. Your first example is using the intrinsic lock of lock
, while the second is using the intrinsic lock of this
. The question is whether or not this
is really what you want to lock on, which it often isn't.
Consider the case, when you use synchronized(this)
inside one of your methods. You have 2 objects of this class, and these objects reference some shared resource. If you lock on this
then you will not have mutual exclusivity to that resource. You need to lock on some object that everything that can access the resource has access to.
Lock on this
ONLY if the important resource is part of the class itself. Even then in some cases a lock object is better. Also, if there's several different resources in your class, that do not need to be mutually exclusive as a whole, but individually, then you need several lock objects.
The key is to really just know how synchronized works, and be mindful of what your code is actually doing