How to avoid deadlock in Java Threads

Today’s post is on breaking Deadlock of multiple Threads : on “November 5, 2014” I had posted a code of creating Deadlock.
Today I am modifying the same code for avoiding such Deadlock. There are many ways to avoid a deadlock but simple rule is: have all threads claim and release their locks in the same order. In this way, you never get into a situation where a deadlock can occur.

My updated code without Deadlock
========================================

public class CustomerUpdateDeadloackThread {

	public static void main(String[] args) {

		Customer cstmr = new Customer("Peter");
		Address adrs = new Address("B-232, Bangalore");

		for (int i = 0; i < 10; i++) {
			new Thread(new TagObjectsToEachOther(cstmr, adrs)).start();
			new Thread(new TagObjectsToEachOther(adrs, cstmr)).start();
		}

	}
}

interface CustomerUpdater {

	public boolean update(Object obj);

}

class TagObjectsToEachOther implements Runnable {
	CustomerUpdater taskItem;
	Object objToUpdateWith;

	public TagObjectsToEachOther(CustomerUpdater cspdtr, Object obj2) {
		this.taskItem = cspdtr;
		this.objToUpdateWith = obj2;
	}

	@Override
	public void run() {
		taskItem.update(objToUpdateWith);
		System.out.println(" Task done :" + Thread.currentThread().getName());
	}

}

class Address implements CustomerUpdater {

	String address;
	Customer customer;

	public Address(String addrs) {
		this.address = addrs;
	}

	@Override
	public boolean update(Object cstmr) {

		synchronized ((Customer) cstmr) { // same order of locks will be used at other places !!!
			synchronized (this) {
				try {
					this.customer = (Customer) cstmr;
					Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time
				} catch (CustomerUpdateFailureException e) {
					e.getCause();
					return false;
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return true;
			}
		}
	}

}

class Customer implements CustomerUpdater {

	String name;
	Address address;

	public Customer(String nm) {
		this.name = nm;
	}

	@Override
	public boolean update(Object adrs) {
		synchronized (this) {
			synchronized ((Address) adrs) { // Maintaining order of accessing lock to avoid deadlock !!!
				try {
					this.address = (Address) adrs;
					Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time
				} catch (CustomerUpdateFailureException e) {
					e.getCause();
					return false;
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return true;
			}
		}
	}

}

class CustomerUpdateFailureException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	@Override
	public String getMessage() {

		return "Uncompitable update";
	}

}

===================  Output =========================

 Task done :Thread-0
 Task done :Thread-9
 Task done :Thread-8
 Task done :Thread-7
 Task done :Thread-6
 Task done :Thread-5
 Task done :Thread-4
 Task done :Thread-3
 Task done :Thread-2
 Task done :Thread-1

use Weak reference for high availability of cache and In-Memory DB operations

We should think about using WeakReference whenever we need a reference to an object, but you don’t want that reference to protect the object from the garbage collector. A classic example is a cache that we want to be garbage collected when memory usage gets too high.

Basically a WeakReference will be GC-d by the JVM eagerly, once the referenced object has no hard references to it. A SoftReferenced object on the other hand, will tend to be left about by the garbage collector until it really needs to reclaim the memory.

Suppose there is a Query level cache and it is persisted and attached to a session. If such queries are very high, certainly they will occupy a huge memory and then they need to be claimed ( GC-d ) as soon as not required. For this, Class Query should be implemented or enqueued through WeakReference.

To reach Big Data take your first step with JSON

Ten years ago, XML was the primary data interchange format. When it came on the scene, it was a breath of fresh air and a vast improvement over the truly appalling SGML (Standard Generalized Markup Language).

But it’s no secret that in the last few years, a bold transformation has been afoot in the world of data interchange. The more lightweight, bandwidth-non-intensive JSON (JavaScript Object Notation) has emerged not just as an alternative to XML, but rather as a potential full-blown successor.The rise of JSON as a key player in database technologies is another bad portent for XML. As it stands, Big Data does not have a preferred data interchange format per se. But the claim that I’d like to make about Big Data and JSON is a bit more specific. What I’d like to argue is that JSON is emerging as a preferred format in web-centric, so-called “NoSQL” databases.

I am putting one JSON example here. you may try to write corresponding XML file and a java Parser for your learning.


{
  "Users": {
    "type": "bank",
    "User": [
      {
        "name": "Ram",
        "Bank": [
          {
            "name": "SBI",
            "UserID": "RamSBI",
            "Password": "RamSBIpwd"
          }
        ]
      },
      {
        "name": "Mohan",
        "Bank": [
          {
            "name": "SBI",
            "UserID": "MohanSBI",
            "Password": "MohanSBIpwd"
          }
        ]
      } 
    ]
  }
}

Safe Singleton for your multi-core servers

Purpose of a Singleton is to have one copy of an object in JVM. But writing below code without volatile in a multi core environment may result in multiple copies of Singleton if any failover occurs.
In a multi-core server multiple Threads of your code may try to create a Singleton object. If singleton variable ( _instance ) is properly not visible to all Threads in all running conditions then Singleton will appear with multiple copies ( which is never expected ).To avoid such cases _instance variable should be declared volatile to make sure if a Thread is creating Singleton instance and just after creation it lost the CPU, all other threads should be communicated that _instance is not null now.

public class Singleton{

private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
} 

Code to produce deadlock between two threads

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Based on number of Threads ( tasks complexity ) and priority Thread Scheduler decides execution plan.  Here my intention is to generate DeadLock so I planned to execute both threads 10 times so that at sometime they will be blocked for locks !

Problem :  Many times we tag records/ Objects for better indexing. Though this will
not be real time problem but I am trying to simulate a similar scenario.
say for some requirement I am tagging a customer with an Address and again
Address with Customer in a social media Analytic Application. To do this
tasks I may need thousands of Threads.
Below is one code which may report deadlock for  such Threads.

===========================================================================================

public class CustomerUpdateDeadloackThread {

public static void main(String[] args) {

Customer cstmr = new Customer("Peter");
Address adrs = new Address("B-232, Bangalore");

for (int i=0; i<10;i++){

// Lets tag a customer and address with each other for  indexing
new Thread(new TagObjectsToEachOther(cstmr, adrs)).start();
new Thread(new TagObjectsToEachOther(adrs, cstmr)).start();
}


}
}

interface CustomerUpdater {

public boolean update(Object obj);

}

class TagObjectsToEachOther implements Runnable {
CustomerUpdater taskItem;
Object objToUpdateWith;

public TagObjectsToEachOther(CustomerUpdater cspdtr, Object obj2) {
this.taskItem = cspdtr;
this.objToUpdateWith = obj2;
}

@Override
public void run() {
taskItem.update(objToUpdateWith);
System.out.println(" Task done :" + Thread.currentThread().getName());
}

}

class Address implements CustomerUpdater {

String address;
Customer customer;

public Address(String addrs) {
this.address = addrs;
}

@Override
public boolean update(Object cstmr) {
synchronized (this) {
synchronized ((Customer) cstmr) {
try {
this.customer = (Customer) cstmr;
Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time
} catch (CustomerUpdateFailureException e) {
e.getCause();
return false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
}

}

class Customer implements CustomerUpdater {

String name;
Address address;

public Customer(String nm) {
this.name = nm;
}

@Override
public boolean update(Object adrs) {
synchronized (this) {
synchronized ((Address) adrs) {
try {
this.address = (Address) adrs;
Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time
} catch (CustomerUpdateFailureException e) {
e.getCause();
return false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
}

}

class CustomerUpdateFailureException extends RuntimeException {

private static final long serialVersionUID = 1L;

@Override
public String getMessage() {

return "Uncompitable update";
}

}

volatile as a boolean flag.

public class VolatileAsFlag extends Thread {
volatile boolean keepRunning = true;

public void run() {
long count = 0;
while (keepRunning) {
count++;
}
System.out.println("Thread terminated." + count);
}

public static void main(String[] args) throws InterruptedException {
VolatileAsFlag t = new VolatileAsFlag();
t.start();
t.getState();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println("keepRunning set to false.");
}
} 

who will dance with Nancy ? Find in below code !

public class DecideDancePair {

DecideDancePair ddp1;
StringBuffer ddp2 = new StringBuffer();

public static void main(String[] args) {

new Thread(new Runnable() {

@Override
public void run() {
synchronized (DecideDancePair.class) {
System.out.println("Its weekend .... Hey Guys !! this is Nancy , who will dance with me? ");
}

}
}).start();

new Thread(new Runnable() {

@Override
public void run() {

synchronized (new DecideDancePair().ddp1) {
System.out.println("Hey Nancy !! this is Peter , I will dance with you.");
}

}
}).start();

new Thread(new Runnable() {

@Override
public void run() {
synchronized (new DecideDancePair().ddp2) {
System.out.println("Hey Nancy !! this is Rozer , I will dance with you.");
}

}
}).start();

}

}

==============================

Answer :
My new post is going to take little more time so thought of to post solution of this problem.

Nancy will always go for dance because she having Lock over a object which is not NULL. same with Rozer , he is also having a non-NULL lock. while poor Peter is caught with NULL object Lock so that piece of code will throw exception below and Hence Nancy and Rozer will de in dance 🙂 !!!

Code execution will looks like :


Its weekend .... Hey Guys !! this is Nancy , who will dance with me? 
Exception in thread "Thread-1" Hey Nancy !! this is Rozer , I will dance with you.
java.lang.NullPointerException
	at BasicConcepts.DecideDancePair$2.run(DecideDancePair.java:26)
	at java.lang.Thread.run(Thread.java:745)