Two instances of a class can simultaneously call a method (Synchronized on some object)

I have a method like:

public void processChildNodes(Node result, Node source) { synchronized (source) { NodeList nodes = source.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { processNode(result, nodes.item(i)); } } } 

Now let me say that I'm trying to call processChildNodes with two different instances of a class in which this method is present with the same source (second parameter of the method). Is it possible that these 2 executions can go in parallel?

+4
source share
4 answers

No, the method will be called, but the contents in the synchronized block will not be executed in parallel. This is because, as you already mentioned, you are using the same source object. since a lock is obtained on the object, synchronization will work properly.

+2
source

You are trying to lock an object. If you pass the same object, then your processing will be synchronized, which means that one thread will execute code inside the synchronized block, and the other thread will wait for it. But if you pass two different objects, then they will use two different locks, which means that they do not depend on each other to make the lock. Therefore, both of them will be executed in parallel.

How you wrote the code and trying to synchronize the execution using the source object. Therefore, make sure that both of your threads use the same source object to get the desired result.

+2
source

Since you are using the source object to synchronize synchronization, it should work correctly. If the objects used in two copies are different, two executions can occur in parallel.

+1
source

Java is bandwidth, which means that the passed Node actually a copy. The system creates two separate copies for two separate method calls, which means that two will be executed in parallel. Please note that this also means that your synchronized block may be inefficient. Be careful with data races.

EDIT

I did a bit more research and found this page that describes how parameters work. Given this new information, I believe my answer is invalid, but I'm still not 100% sure.

0
source

Source: https://habr.com/ru/post/1480635/


All Articles