Considering the following code snippet:
Object bar1 = new ... ;
Object bar2 = new ... ;
Object foo = (either bar1 or bar2) ;
Now, foo can be either bar1 or bar2 at various times of the programs. I just wanted to check that synchronized(foo) will lock the corresponding bar1 or bar2. This seems like the most likely scenario given that objects aren’t copied in Java. Is this correct?
will lock on
foo==bar1.However this is a weird and error-prone construct. For example:
Now you have 2 threads running your synchronized block concurrently. I can’t really find a reason why you would want that. And if you do, then the block should probably not be synchronized and you should use a different locking strategy.
See also this related post.