who will dance with Nancy ? Find in below code !

My new post is going to take little more time so thought of to post solution of this long pending problem posted by me on November 1, 2014

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();

}

}

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

Soln :

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 below exception and Hence Nancy and Rozer will be 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)

Shared queue processing with Pub and Sub Threads

import java.util.Random;

public class PubSubDemo {

	public static void main(String[] args) {
		SharedQ sharedQ = new SharedQ();

		new Thread(new Consumer(sharedQ), "Consumer").start();
		// Delay publishing
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(new Producer(sharedQ), "Producer").start();
	}

}

class Producer implements Runnable {
	SharedQ sharedQPro = null;

	public Producer(SharedQ sharedQ) {
		this.sharedQPro = sharedQ;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			produce();
		}
	}

	public void produce() {
		synchronized (sharedQPro.sharedQueue) {

			for (int i = 0; i < 3; i++) {
				sharedQPro.sharedQueue[i] = (new Random().nextInt(20));
				System.out.println(" ### Produced ### " + sharedQPro.sharedQueue[i]);
			}
			sharedQPro.sharedQueueIsEmpty = false;
			sharedQPro.sharedQueue.notify();
			try {
				sharedQPro.sharedQueue.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

class Consumer implements Runnable {
	SharedQ sharedQCon = null;

	public Consumer(SharedQ sharedQ) {
		this.sharedQCon = sharedQ;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			consume();
		}
	}

	public void consume() {
		synchronized (sharedQCon.sharedQueue) {
			if (sharedQCon.sharedQueueIsEmpty) {
				try {
					sharedQCon.sharedQueue.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			System.out.println();

			for (int i = 0; i < 3; i++) {
				System.out.println(" *** Consumed *** " + sharedQCon.sharedQueue[i]);
				sharedQCon.sharedQueue[i] = 0;
			}
			sharedQCon.sharedQueue.notify();
			System.out.println(" --------------------------");
			try {
				sharedQCon.sharedQueue.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

class SharedQ {

	int[] sharedQueue = new int[3];
	boolean sharedQueueIsEmpty = true;

}

/*
Output of pub sub :

 ### Produced ### 1
 ### Produced ### 0
 ### Produced ### 3

 *** Consumed *** 1
 *** Consumed *** 0
 *** Consumed *** 3
 --------------------------
 ### Produced ### 12
 ### Produced ### 0
 ### Produced ### 14

 *** Consumed *** 12
 *** Consumed *** 0
 *** Consumed *** 14
 --------------------------
 ### Produced ### 13
 ### Produced ### 8
 ### Produced ### 17

 *** Consumed *** 13
 *** Consumed *** 8
 *** Consumed *** 17
 --------------------------
*/

Sequence generator tasks by Threads

Many times we face scenario where we need to execute two sequential tasks to perform a operation, like Tagging / Stamping serial Coupons , Producing serial Tickets at different Vending Machines. Below code ( generating Odd and Even in sequence) can be used for such requirement.

PS: This is a basic implementation, the same can be done using other Threading concepts.

				
package multithreading;

// print ODD and Even number alternatively

public class SquenceGeneratorTasks {

	public static boolean oddPrinted = false;

	public static void main(String[] args) {
		 Object lock =new Object();
		Thread oddThread = new Thread(new Runnable() {

			@Override
			public void run() {
				int i = 1;
				while (i <= 20) {

					synchronized (lock) {
						if (!oddPrinted) { // make sure printing starting with Odd number and each Odd is followed with a Even number
							System.out.println(i);
							i = i + 2;
							oddPrinted = true;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				}
			}
		});

		
		Thread evenThread = new Thread(new Runnable() {

			@Override
			public void run() {
				
				System.out.println(" Though you have delayed Odd thread but printing gonna start with Odd number only !!");
				
				int i = 2;
				while (i <= 20) {
					synchronized (lock) {
						if (oddPrinted) {
							System.out.println(i);
							i = i + 2;
							oddPrinted = false;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		});

		evenThread.start();
		
		// even if We apply some delay to Odd thread printing will start with ODD number only and 
		// Sequence of Odd-Even-Odd maintained
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		oddThread.start();

	}

}						
/*
Though you have delayed Odd thread but printing gonna start with Odd number only !!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 */

You can download the same code from : https://github.com/SkilledMinds/easyNuts/tree/master/code-25-09-2015

Thread.sleep() can ditch your join()’s expected code execution , see it how !!


public class JoinWithSleep
{

    public static void main(String[] args)
    {

        Thread t1 = new Thread(() -> {
            System.out.println(" In :: Thread t1");

        });

        Thread t2 = new Thread(() -> {
            System.out.println(" In :: Thread t2");
            try
            {
                t1.join();
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(" Out :: Thread t2");
        });

        try
        {
            t2.join();
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        t2.start();
        
        // this single sleep can ruin your code !!
        try
        {
            Thread.sleep(4000);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t1.start();

    }

}



/*
Without Sleep
In :: Thread t2
In :: Thread t1
Out :: Thread t2

With Sleep
In :: Thread t2
Out :: Thread t2
In :: Thread t1

*/

check your java class locking and classloader concept.

try below code to test your concept of class Locking and classLoader. I will post the
reason of output next week till then you do your finding !!

public class VerifyClassLoadingOnClassLock {
    public static void main(String[] args) {
        show();
    }

    private static void show() {
        synchronized (SharedQ.class) {
            System.out.println(" Method Show() executing from Main() .... ");
        }       
    }
} 



class SharedQ {  
    static {
        System.out.println(" Classloader is loading SharedQ ");
    }

    public static void writeStream() {
        // some multiThread code here
    }
}

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 &lt; 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(&quot; Task done :&quot; + 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 &quot;Uncompitable update&quot;;
	}

}

===================  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

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&lt;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";
}

}