What is the difference between synchronized on lockObject and using this as the lock?

Personally I almost never lock on “this”. I usually lock on a privately held reference which I know that no other code is going to lock on. If you lock on “this” then any other code which knows about your object might choose to lock on it. While it’s unlikely to happen, it certainly could do – and could cause deadlocks, or just excessive locking.

There’s nothing particularly magical about what you lock on – you can think of it as a token, effectively. Anyone locking with the same token will be trying to acquire the same lock. Unless you want other code to be able to acquire the same lock, use a private variable. I’d also encourage you to make the variable final – I can’t remember a situation where I’ve ever wanted to change a lock variable over the lifetime of an object.

Leave a Comment