What is deadlock?
When two or more threads waiting for each other to relinquish resource, which both threads are unable to do and loop infinitely, is called deadlock. This issue only happens in a multi-threading application.
There is no simple way of detecting deadlocks other than following the code meticulously. There are tools available which can high light deadlock. These deadlocks were most common prior to Java 5. In java 5 tryLock and other techniques are available to avoid the deadlock. Thread dump in the Linux environment provides stack trace for a deadlock. There are commands like kill -3 is also available, JCONSOLE will also show which threads are getting locked and a much better interface.
public void demoDeadlockMethod1(){
synchronized (Boolean.class) {
log.info(“Acquired lock on Boolean.class object”);
synchronized (Short.class) {
log.info(“Acquired lock on Short.class object”);
} } }
public void demoDeadlockMethod2(){
synchronized(Short.class){
log.info(“Acquired lock on Short.class object”);
synchronized (Boolean.class) {
log.info(“Acquired lock on Boolean.class object”);
} } }
If demoDeadlockMethod1() and demoDeadlockMethod2() both will be called by two or many threads in our application, as it can be seen that locks acquiring and realising in the wrong order, hence deadlock will appear at some time in the application. Now when deadlocks both waits on each other to release the locks, which in our case not possible.
Solution to remedy would be to realse locks in the right order as follows:
public void demoDeadlockMethod1(){
synchronized (Short.class) {
log.info(“Aquired lock on Short.class object”);
synchronized (Boolean.class) {
log.info(“Aquired lock on Boolean.class object”);
} } }
public void demoDeadlockMethod2(){
synchronized (Short.class){
log.info(“Aquired lock on Short.class object”);
synchronized (Boolean.class) {
log.info(“Aquired lock on Boolean.class object”);
} } }
Hopefully here there will no deadlock because demoDeadlockMethod1 and demoDeadlockMethod2 are entering locks in the same order and releasing in the same order.
Please visit Business Integration Software to see various products using locking for synchronization and avoiding deadlocks.
Assessment Management Software
Multiple Choice Question Software