How to achieve parallel code execution without user Threads

What comes to your mind when you have to run a piece of code in parallel? you will create some threads to do it, correct! But this is not only a way to achieve it. Recently I came across one interesting requirement where I had to run a piece of code of an API for three parallel calls (without Threads).My approach is not something new,¬†many of you might be doing it already and others might have not noticed this approach while maintaining the legacy code ūüôā .

Well, so this approach is nothing but a combination of Bean loading in Spring container and corresponding mapped Java class execution, and hooking a API to support parallelism. when spring container loads a annotated/configured Bean it executes Java method associated with it. using this concept we can define and load the same bean with three different ids to execute the method ( the same code runnable implementation ) code rather than doing it through Three different threads.


<beans profile="cluster">
<bean id="mongoQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>
</beans>
<beans profile="cluster">
<bean id="cassandraQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>
</beans>
<beans profile="no_cluster">
<bean id="graphQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>
</beans>

Above piece of code is just a replacement of Three threads for  "cacheQueryProcessor" task, now to achieve parallelism/conditional task execution this method should be designed properly to meet the requirement. For more details on parallelism/conditional task execution please refer Spring-Batch Scaling and Parallel Processing or Java executor framework ( which is a base of every Parallelism implementation).

Still you want to take a deep dive of similar implementation then take a look at ongoing Spring Jira https://jira.spring.io/browse/SPR-8767

PS: For an experienced java professional this may look very simple to do but considering this in a bigger picture gives the insight of an option to design an utility tool/Jar without heavy Spring batch or similar APIs.

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

*/

custom linkedList implementation

Computing systems are concerned with the storage and retrieval of information.For systems to be economical the data must be organized (into data structures) in such a way as to support efficient manipulation (by algorithms).Choosing the wrong algorithms and data structures makes a program slow at best and unmaintainable and insecure at worst.

Lets take an example of purchase order of an e-commerce store. If purchase order implemented as custom linkedlist then we can take benefit of

a) constant-time insertions/deletions from the list
b) maintaining many versions of purchase order without any additional complexity.
c) to insert items in the middle of the list (such as a priority queue)
d) many priority queue based operation
e) In-memory operations

below is one such implementation

 
package com;

import java.util.Iterator;

public class LinkedListDemo {

	public static void main(String[] args) {

		LinkedList lnkls = new LinkedList();
		lnkls.add(11);
		lnkls.add(12);
		lnkls.add(13);
		lnkls.add(14);
		lnkls.add(15);
		lnkls.add(16);
		lnkls.add(17);
		lnkls.add(18);
		System.out.println("Total added items :" + lnkls.size);
		Iterator<LinkedList.Node> it = lnkls.iterator();

		System.out.println("****** Items of LinkedList ******");

		while (it.hasNext()) {
			System.out.println(it.next().objValue);
		}

	}
}

class LinkedList implements Iterable<LinkedList.Node>, Iterator<LinkedList.Node> {

	Node head;
	Node lastNode;
	Node visitorNode;

	int size = 0;
	int visited = 0;

	public LinkedList() {
	}

	public void add(Object o) {
		Node newNode = new Node(o);

		if (this.head == null) {
			this.lastNode = this.head = newNode;
		} else {
			this.lastNode.next = newNode;
			this.lastNode = newNode;
		}
		size++;
		System.out.println("Added " + newNode);
	}

	@Override
	public Iterator<LinkedList.Node> iterator() {
		visitorNode = lastNode = head;
		return this;
	}

	@Override
	public boolean hasNext() {
		if (visited++ < size)
			return true;
		else
			return false;
	}

	@Override
	public Node next() {
		Node visitedNode = lastNode;
		lastNode = lastNode.next;
		return visitedNode;
	}

	class Node {

		Object objValue;
		Node next;

		public Node(Object o) {
			this.objValue = o;
			this.next = null;
		}

		@Override
		public String toString() {
			return objValue.toString();
		}

	}
 // additional operational and supportive APIs for custom linkedlist
}

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