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?
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.
The whole purpose of a synchronized block is to prevent what you are asking, so you would have to remove the synchronized block.
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