M
M
MaxLich2017-05-04 12:07:58
Java
MaxLich, 2017-05-04 12:07:58

What is the purpose of specifying an object in a synchronized block?

Java has a synchronized(obj) {} construct. What is the purpose of specifying some object obj in parentheses? Is this just used as a label to separate different sync blocks from each other? The object itself is not blocked, and you can do anything with it outside the synchronization block?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
etorkhov, 2017-07-21
@etorkhov

You use the synchronization block to synchronize actions across multiple parallel threads. For synchronization to work, these threads must receive the same parenthesized object instance. So not a label, but an object instance.
And it can be, for example, some object-property of a class, then only threads within one instance of this class will be synchronized. Those. different streams for different instances in this location will not be synchronized.
Or static. In the latter case, all threads will be synchronized.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question