I've come across code like the following several times
class Foo {
private Object lock = new Object();
public void doSomething() {
synchronized(lock) {
...
What I'm interested in is why a lock object is created instead of writing synchronized(this)
? Is it there to enable sharing the lock? I vaguely remember reading that it is an optimization. Is that true? Also, does it, in some context, make sense to have the lock declared as final
?
It means that this block of code is synchronized meaning no more than one thread will be able to access the code inside that block. Also this means you can synchronize on the current instance (obtain lock on the current instance).
concurrent package has a whole range of classes that can be used to make multi-threaded code thread-safe without explicitly using the "synchronized" keyword, if that's what you're asking. The ThreadLocal class may also help, as may the "volatile" keyword.
A synchronization object is an object whose handle can be specified in one of the wait functions to coordinate the execution of multiple threads. More than one process can have a handle to the same synchronization object, making interprocess synchronization possible.
Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time.
Imagine a scenario where you have thread1
and thread2
access method1
, thread3
and thread4
access method2
. Synchronizing on this
would block thread3
and thread4
if thread1
or thread2
are accessing method1
which should not happen as thread3
and thread4
have nothing to do with method1
. An optimization for this is to use two different locks instead of locking on the whole class instance.
Here is a nice paragraph I found on JavaDoc that reflects this:
Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking
this
is discouraged because if the object itself is used as a lock from the outside it would break the internal synchronization. Also, remember that synchronized
methods are also using this
as a lock, which may cause an unwanted effect.final
is recommended to prevent a situation in which a lock object is reassigned inside a synchronized
block, thus causing different threads to see different lock objects. See this other question: Locking on a mutable object - Why is it considered a bad practice?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With