Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can two threads access a synchronized block simultaneuously [closed]

I was asked in an interview of how two threads can access a synchronized block simultaneously, but I cannot come up with a scenario it might happen. Is it possible for two threads to access a synchronized block simultaneuously?

like image 336
Meastro Avatar asked Mar 21 '23 17:03

Meastro


2 Answers

The reason for having synchronized blocks is to prevent two threads from accessing that block simultaneously. This of course only holds if the two threads synchronizes over the same object. If you for instance does something like this:

synchronized (new Object()) {
// Multiple threads can execute here at the same time.
}

Multiple threads can then execute in the same block at the same time.

like image 63
Aleksander Blomskøld Avatar answered Apr 07 '23 11:04

Aleksander Blomskøld


The whole purpose of a synchronized block is to prevent what you are asking, so you would have to remove the synchronized block.

like image 37
Scary Wombat Avatar answered Apr 07 '23 13:04

Scary Wombat