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

*/

What Is Middle Tier Clustering?

Middle tier clustering is just a cluster that is used for service the middle tier in a application. This is popular since many clients may be using middle tier and a lot of heavy load may also be served by middle tier that requires it be to highly available.

Failure of middle tier can cause multiple clients and systems to fail, therefore its one of the approaches to do clustering at the middle tier of a application.

In java world, it is really common to have EJB server clusters that are used by many clients. In general any application that has a business logic that can be shared across multiple client can use a middle tier cluster for high availability.

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
}

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

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.

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;
}