Friday, August 16, 2013

Java Thread Join method

Java thread is essentially a final method which cannot be overridden. If there are two threads t1 and t2, when t2.join() is executed from thread t1, then thread t1 waits for t2 to complete execution before attempting to proceed it's own execution. If a sleeping thread is interrupted by a join() method, then an interruptedexception is thrown.

One of the main use cases of join - while implementing cache, have the initializing thread execute before having other code execution. Serializing 2 functions.

With Java 5, there are two techniques - CyclicBarrier and CountDownLatch to implement thread scenarios of executing one thread after another.

Another cool feature of Java5, that helps use of TimeUnit -
TimeUnit.SECONDS.sleep(2); makes the existing thread wait for 2 minutes and then complete execution.

public class ThreadJoinExample{
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Thread running " + Thread.currentThread());
Thread t1 = new Thread() {
public void run() {
try {
System.out.println("Thread running " + Thread.currentThread());
TimeUnit.SECONDS.sleep(2);
System.out.println("Thread running " + Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread finished " + Thread.currentThread());
}
}


Sunday, August 11, 2013

How to Implement a ConcurrentLRUCache

Although there are several third party cache available in Java such as enCache, soCache, Guava library - It's actually easy and important to know how to write a custom LRUCache (last recently used cache).
Simply put a cache is data loaded in to memory identified by a 'key'.
A ConcurrentLRUCache is essentially backed up by a ConcurrentHashMap and controlled by a ConcurrentLinkedQueue.

So let's see the sample code -

public class ConcurrentLRUCache<Key, Value> {
      private final int maxSize;
      private ConcurrentHashMap map<key, value>;
      private ConcurrentLinkedQueue queue<key>,

     public ConcurrentLRUCache(int maxSize) {
          //Set the size of map
          this.maxSize = maxSize;
          map = new ConcurrentHashMap<key, value>(maxSize);
          queue = new ConcurrentLinkedQueue();
    }

    public put(final Key key, final Value value) {
       //If map already contains the key, you want to reinsert a new value for existing item, then remove the item from queue to maintain FIFO order (the key gets added to queue in the end of the method
        if(map.containsKey(key) {
           queue.remove(key);
       }

       //If the Size of queue is full, remove the first element added from map and queue
       if(queue.size >= maxSize) {
          //Retrieves the oldest element added and removes it from queue
           key oldestKey = queue.poll;
           if(oldestKey != null) {
              //Remove oldest element added to the map
              map.remove(oldestKey);
          }    
       }

       //Add value to map and queue
       queue.put(key);
       map.add(key, value);
    }
   
    public get(final Key key) {
        return map.get(key);
    }
}







}

Friday, August 9, 2013

Immutability - Custom Immutable Class

Java provides a mechanism in which you can create custom Immutable classes. By default, classes like String, Integer and other wrapper classes are immutable. So, what's the main advantage of a class being immutable -

a. An Immutable class is essentially thread-safe and is an ideal candidate for creating them in multi-threaded application.
b. Use of synchronized code is minimized in a multi-threaded application by use of immutable objects.
c. Since their states cannot be altered once they are created, they are excellent candidates as 'keys' for HashMaps.
d. Their re-usability is another good reason to create them, since it can be cached and can be set once in static initializers and used everywhere.

How to create an immutable class -

a. The Object has to be declared final.
b. All the members of the object has to be declared final. No setters method allowed.
c. Object should be constructed properly, i.e. should not result in leak during construction.

public final class ImmutableClass {
       private final String name;
       private final Integer age;
       private final Date dob;

       public ImmutableClass(name, age, dob) {
          this.name = name;
          this.age = age;
          this.dob = dob;
       }

       public String getName() {
         return name;
       }

       public Integer getAge() {
          return age;
       }

       //Mutable Object to prevent setting internal value - create a copy of the date and return a new date
       public Date getDob() {
          return Date(dob.clone());
       }            
}