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)

Sample code for Producer n Consumer Problem

There are at least 5 direct ways to write a Producer n Consumer Problem. The basic is one which use wait() and notify().

// Queue
class CustomerQueue
{

    String sharedCustomerQueue[] = new String[5];
}

// Client
public class ProducerConsumerQ
{

    static int NEED_TO_SERVE_BATCH = 2;

    public static void main(String[] args)
    {

        System.out.println(" Producer will fill SharedQueue with 5 elements in each batch.");
        System.out.println(" Consumer will consume elements available in SharedQueue in each batch.");

        System.out.println(" Total " + NEED_TO_SERVE_BATCH + " will be served.");
        System.out.println(" \n ***************************************************************************** ");
        CustomerQueue cq = new CustomerQueue();
        Thread pro = new producer(cq);
        Thread con = new consumer(cq);
        pro.setName("Producer");
        con.setName("Consumer");
        pro.start();
        con.start();

    }

}

class producer extends Thread
{

    int count = 0;
    CustomerQueue qp;

    public producer(CustomerQueue q)
    {
        qp = q;
    }

    @Override
    public void run()
    {

        while (count < ProducerConsumerQ.NEED_TO_SERVE_BATCH)
        {
            System.out.println("\n");
            synchronized (qp.sharedCustomerQueue)
            {

                // everytime generate 5 random numbers and put in Queue
                for (int p = 0; p < 5; p++)
                {
                    qp.sharedCustomerQueue[p] = (int) ((Math.random() * 10) % 10) + "";
                    System.out.println("Producer : Genereated item is :" + qp.sharedCustomerQueue[p]);
                }
                qp.sharedCustomerQueue.notify();
                try
                {
                    qp.sharedCustomerQueue.wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                count++;
            }
        }

    }
}

class consumer extends Thread
{

    int count = 0;
    CustomerQueue qc;

    public consumer(CustomerQueue q)
    {
        qc = q;
    }

    @Override
    public void run()
    {

        while (count < ProducerConsumerQ.NEED_TO_SERVE_BATCH)
        {
            if (qc.sharedCustomerQueue[0] != null) // consume only if queue is filled
            {
                synchronized (qc.sharedCustomerQueue)
                {

                    for (String qItem : qc.sharedCustomerQueue)
                    {
                        System.out.println("Consumer : Consuming item " + qItem);
                    }

                    System.out.println("\n");
                    qc.sharedCustomerQueue.notify();

                    try
                    {
                        qc.sharedCustomerQueue.wait();
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }

    }
}

/*
 Producer will fill SharedQueue with 5 elements in each batch.
 Consumer will consume elements available in SharedQueue in each batch.
 Total 2 will be served.
 
 ***************************************************************************** 
Producer : Genereated item is :3
Producer : Genereated item is :5
Producer : Genereated item is :5
Producer : Genereated item is :1
Producer : Genereated item is :1
Consumer : Consuming item 3
Consumer : Consuming item 5
Consumer : Consuming item 5
Consumer : Consuming item 1
Consumer : Consuming item 1




Producer : Genereated item is :9
Producer : Genereated item is :5
Producer : Genereated item is :8
Producer : Genereated item is :9
Producer : Genereated item is :8
Consumer : Consuming item 9
Consumer : Consuming item 5
Consumer : Consuming item 8
Consumer : Consuming item 9
Consumer : Consuming item 8



*/

A Practical scenario for using volatile in java

working example of “volatile” for Java7+ is a highly used searching keyword
for java guys. After lots of search people hardly get any working and effective
code on Volatile. So I decided to put one sample code here on Volatile.

A short note on volatile #
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. Java guarantees that value of volatile variable will always be read from main memory and not from Thread’s local cache.So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. This guarantees visibility of changes made by one thread to another thread also.Java volatile keyword cannot be used with method or class
and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

Below is one example based on volatile, in which different Threads will try to search a number is different range if any thread finds the number search operation will be stopped by all Threads.

 public class SerachUsingVolatile {

	// search range starts with
	static int START = 0;
	static int END = 10000;

	public static void main(String[] args) {

		NumberFinder t = new NumberFinder(28000);

		Thread t1 = new Thread(t, "T1");
		Thread t2 = new Thread(t, "T2");
		Thread t3 = new Thread(t, "T3");

		t1.start();
		t3.start();

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		t2.start();

	}

}

class NumberFinder implements Runnable {
	//volatile boolean keepRunning = true;
        boolean keepRunning = true;
	int numToFind;

	NumberFinder(int nf) {
		this.numToFind = nf;
	}

	public void run() {

		int start = SerachUsingVolatile.START;
		int end = SerachUsingVolatile.END;

		// move range of search for each Thread
		SerachUsingVolatile.START = SerachUsingVolatile.START + 10000;
		SerachUsingVolatile.END = SerachUsingVolatile.END + 10000;

		while (keepRunning) {

			for (int i = start; i <= end; i++) {
				if (i == numToFind) {
					keepRunning = false;
					System.out.println("Target found by Thread: " + Thread.currentThread().getName()
							+ " rest all Threads should stop searching !!! ");
				}
			}
		}
		System.out.println(" Search stopped for Thread :" + Thread.currentThread().getName());
	}
}

**************************************************
Output with volatile :

Search stopped for Thread :T1
Target found by Thread: T2 rest all Threads should stop searching !!!
Search stopped for Thread :T3
Search stopped for Thread :T2

Output without volatile :

Target found by Thread: T2 rest all Threads should stop searching !!!
Search stopped for Thread :T2

*************************************************

That’s all Guys !!!! I am open for your questions n comment 🙂