I have this code in Java:
public void doSomeThing() { synchronized (this) { doSomeThingElse(); } } public void doSomeThingElse() { synchronized (this) { // do something else } }
Can this code block? I mean, Can this code wait for ever?
public void doSomething() { synchronized(lock1) { synchronized(lock2) { // ... } } } public void doOtherthing() { synchronized(lock2) { synchronized(lock1) { // ... } } } now if more than one thread are trying to access these methods then there may be a deadlock because of nested synchronized blocks.
The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized , so only one thread can execute any of them at a time.
Nested monitor lockout is a problem similar to deadlock. A nested monitor lockout occurs like this: Thread 1 synchronizes on A Thread 1 synchronizes on B (while synchronized on A) Thread 1 decides to wait for a signal from another thread before continuing Thread 1 calls B.
From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it. However the practical difference between synchronizing a method vs. a code block really depends on the method and what code is being left out of the synchronized block.
As the java documentation describes for Reentrant locking:
a thread can acquire a lock that it already owns
The second synchronized block is using the same lock and thus will always be useable as the lock has already been aquired in the outer method.
No, there will not be a deadlock.
If a thread owns the lock on this
, it will go into other synchronized
methods/block like hot knife in butter.
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