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


Tuesday, July 30, 2013

HashSet vs TreeSet

- Both Hashset and Treeset implement the java.util.set interface
- Since they implement the set interface, by contract they do not allow any duplicates
- Both the implementations are not synchronized and hence they are not thread-safe. However, they can be made thread-safe by invoking the Collections.synchronizedSet() method.
- The main difference between the two is ordering, i.e. TreeSet maintains an ordered collection, whereas a HashSet does not maintain order
- If your implementation does not require any order and needs a faster collection, then go for HashSet.
- One other main important difference is HashSet does allow null, whereas, TreeSet, does not allow any null objects.
- The reson for the above would be that HashSet use equals() method to compare two objects in a Set, whereas, TreeSet uses compareTo() method which compare keys and hence it throws a NullPointerException if any null object is inserted into a TreeSet. (needs to be confirmed)

Monday, July 29, 2013

Class Loaders

-Class loaders are java classes which is used to load class files in java from either a file system, network or any other source.
- There are three default class loaders used by java - bootstrap, extension and system class loaders of the Application Class loader.
- Every JVM has primordial or bootstrap class loaders which loads the java.* packages and rt.jar/i18n jar.
- There are non-primordial class loaders such as Extensions which loads the java extension packages.
- Then there is system class loaders, that loads all the class defined in the class path.
- Class loaders are hierarchical and follow a delegation model.
- The parent class has no visibility to child class, however, the child class has visibility to all the parent classes.
- Two sibling classes does not have visibility of each other, but they can see the parent class loaders.
- A class is never reloaded and during initialization the child request the parent to load the classes first and hence the uniqueness of class in maintained.

- class.getClassLoader.getParent() gets the parent class loader
- A class can be loaded by class.forName(class name) or class.forName(class name, initialized, class loader), based on which the classLoader calls the class.loadClass() method which in-turn calls the class.findClass() to locate the bytecodes of the actual class to load.

- It is recommended that any class which overrides Class Loader overrides this findClass instead of loadClass, since loadClass internally calls findClass for class loading.


Saturday, July 6, 2013

Difference between NoClassDefFoundError and ClassNotFoundException in Java

JVM throws NoClassDefFoundError when a static loading of class takes place and a class does not exist. Usually, this means that the class is present at the compile time and class loader isn't able to locate class at runtime. However, NoClassDefFoundError is mostly caused by dynamic loading of classes during runtime using reflection. Class.forName, ClassLoader.findSystemClass, ClassLoader.loadClass.

A detailed account of how to handle NoClassDefFoundError can be found here.. http://javarevisited.blogspot.com.au/2011/06/noclassdeffounderror-exception-in.html

Chief things to remember from the above blogpost -
a. Check for Class Path
b. Check for missing JAR
c. Check for JAR permissions
d. Since NoClassDefFoundError is sub-class of LinkageError, could be a linkage issue.
e. Check for Static load Initialization failure
f. Multiple Class loaders in J2EE environment
g. Check for typo in Bean initialization xml files

Java - Reverse a String

You can reverse a string using many methods in Java -
    String strToReverse = "Hello World";
a. Use StringBuffer reverse() method
    String reverse = new StringBuffer(strToReverse).reverse().toString();
b. Use StringBuilder reverse() method (However this is non-thread safe) method
    reverse = new StringBuilder(strToReverse).reverse().toString();
c. Use own logic to reverse string
    reverse = reverse(strToReverse);

    public static String reverse(String strToReverse) {
    String reverse = "";
     if(strToReverse == null || strToReverse.isEmpty()) {
             return strToReverse;
    }

    for(int i = strToReverse.length() - 1; i >=0 ; i--) {
        reverse = reverse + strToReverse.charAt(i);
    }
     return reverse;
  }