Wednesday, March 30, 2016

Fork Join vs ExecutorService

Heading of  this article is deceptive, as both fork join and executives suffice different needs and they are meant to handle different kinds of parallel/concurrency tasks. But since in  many scenarios we can
use them interchangeably, it is important to understand difference between them.

ForkJoin framework internally uses a special thread pool knows as ForkJoinPool, based on executorservice.  But Fork Join pool has following distinctive properties.

1. It uses work stealing algorithm, hence no of idle workers  are less and can be faster.
2. It manages the pool size dynamically
3. ForkJoin pool threads are daemon threads. Hence we do not need to explicitly shutdown them as we do in executorservice with  "executorService.shutdown()".


ForkJoin pool are meant to handle a task that can be broken down into many smaller tasks and solve them recursively. ExecutorService is helpful for executing independent tasks .

Tuesday, March 29, 2016

Thread Local

A single instance of ThreadLocal can store different values for each thread separately.Values set on a thread local instance is
specific to the current Thread and any other code/logic running on this thread can see the same value, but not the values set on the thread local
instance by some other thread.

How Long Thread Local will be alive?

I have found following articles are quite explanatiry to understand pit falls of ThreadLocal.

refer :
http://javarevisited.blogspot.in/2013/01/threadlocal-memory-leak-in-java-web.html
https://plumbr.eu/blog/locked-threads/how-to-shoot-yourself-in-foot-with-threadlocals

Sunday, March 27, 2016

Explicit Locking

Before java 5, we had to use synchonized keyword to lock an execution. This mechanism had couple of disadvantages
1. There was  no way to separate out read and write of an object with synchonized mechanism. Ideally in many scenarios, allowing multiple threads to read an object is harmless.

2. For time out, we needed wait/notify mechanism along with synchronized  .

3.There was no way to "attempt" to acquire a lock without waiting for other thread to release the
  relevant lock.

Java  5 has introduced two interfaces java.util.concurrent.locks.Lock and java.util.concurrent.locks.ReadWriteLock  . Though internal mechanism,memory access to perform actions on an shared object in a multi-threaded environment is same with old synchronized way, Lock and ReadWritLock provides  more functionalities/flexibility on performing actions on a shared object.

Classification of explicit locking:

1. Lock : This interface provides basic mechanisms to acquire and release lock, It stands out from its cousin "synchronized" by providing non-blocking and interruptible  locking.
Few implementations of Lock: ReentrantLock, ReadLock,WriteLock


2. ReadWriteLock:  ReadWriteLock maintains  a pair of associated locks, one for read and another for write.  The readLock can be hold by multiple threads to read, but writeLock is exclusive.
ReentrantReadWriteLock is an implementation of ReadWriteLock.









Saturday, March 26, 2016

Class level Lock vs Instance Lock

Each java class and its instance  have its associated intrinsic lock.

For a particular class, a  JVM will load its .class only one with a particular class loader. The static members of a class belong to a .class instance. Hence acquiring  class level lock, we can have synchronization mechanism for static members of a class. Having lock on class level , will lock
access to non static methods too by another thread.

Lets consider a class Test1, it has few static methods and few non static methods.

class Test1 {

public  static synchronized void doStuffStatic1(){
System.out.println("invoking static method 1 ####");

}

public  static synchronized void doStuffStatic2(){
System.out.println("invoking static method2####");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void doStuff1(){
System.out.println("invoking instance method 1####");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void doStuff2(){
System.out.println("invoking instance method 2####");

}

}

If a thread acquires a class level lock, another thread can not access any of its static or non-static
 methods.

public static void main(String[] args) {

Test1 test = new Test1();

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {

synchronized (Test1.class) {
test.doStuff1();

}
}
});

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {


Test1.doStuffStatic1();
test.doStuff2();


}
});

t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();


}


static final vs final

We know that static final are used to define constants and a static to define class level members. But
how and when they are loaded?

Lets take an example

class Test{

static final int x=10;
static int y=20;

public static void main(String []args){
    int var1=x;
    int var2=y;

}
}

compile it, and decompile the .class file
you will see something like this

class Test
{
  static final int x = 10;
  static int y = 20;
 
  public static void main(String[] paramArrayOfString)
  {
    int i = 10;  ----> the static final varible is loaded and used in compile time itself
    int j = y;
  }
}

java compiler does some kind of optimization and since a constant(static final) will not be changed, it assigns it in compile time itself

Friday, March 25, 2016

Static Class Loading vs Dynamic Class Loading

When we create a object with new operator , that class is loaded with static class loader. With static class loader class definition is loaded in compile time.
With static class loading , we can construct an object with either no arg/args constructors.

There are very less chances for runtime exception with new operator. Only rare case is when the class was present during compile time but was not available on classpath during runtime.  In that case we will get "NoClassDefFoundError"

Dynamic class Loading :
 With a name of a class, we can load a class on runtime too.

  A a = (A) Class.forName("A").newInstance();

Dynamic class loading needs the class to have a no arg constructor.Otherwise in runtime,
we will get exeption(java.lang.NoSuchMethodException)

But dynamic class loading is slower.  The JVM will locate the class, instantiate it with reflection(look up for a no arg constructor) , then typecast it.
If the mentioned class is not found , dynamic class loading will throw "ClassNotFoundException".

We can create a class instance dynamically by using Class.forName("className") or by
using loadClass of a classLoader, ex ClassLoader.getSystemClassLoader().loadClass("className");

the forName() once loads a class using the current class loader and it initializes all static members of the class.
But loadClass() does not initialize static members of the class , unless it is used first time.

ex :

class TestClass1{
static {

        System.out.println("Static Initializer Called!!"};


}
        }

Class.forName("TestClass1") --> will print  "Static Initializer Called!!";
ClassLoader.getSystemClassLoader().loadClass("TestClass1") --> will not print

Use finally Block carefully

One should be careful on using finally block.
Finally block should be used only to close any resource, or avoid using it if resource implements AutoClosable interface.
Few bad usage of finally :

Bad Usage 1:  do not return a value from finally. It will override the value returned from try block.
 
   public int getValue(){
try{
return 10;
}finally{
return 20;
}
}

getValue() will return 20;

Bad Usage 2: Do not eat an exception thrown in try with some unrelavent exception/or a return value in finally .

     public int getValue(){
try{
throw new Exception("a exception");
}finally{
return 20;
}
}

We will have no idea about an exception that has occurred in getValue(). 
   

Try with resources

Try-With-Resources

Before Java 7, finally blocks were put to close any resource allocations inside try block.

ex: 
   public void readFile(){

     FileInputStream input=null;
    try{
             input = new FileInputStream ("C:/myfile.txt");
             int data =input.read();
         }catch(Exception e){
          }finally{
              if(input!=null){
                         input.close();
                               }
}
}

In Java 7 we dont need to explicitly close the inputstream, if use the try with resources.
     ex:
          try(FileInputStream inputFile=new FileInputStream("C/myFile.txt")){

     }catch(Exception e){
    
     }

try can have multiple statements in the parenthes, provided each statement creates an object which implements java.lang.AutoClosable interface.

in pre java 7 try-catch-finally model, if an exception occurs in try and another in finally, the exception thrown in finally used to propagate. This don't give us a clear idea of what was the 
exception occured in the try catch.

In Try with resource, it is resolved. If exception occurs in try and during closing the resources,
the exception thrown in try block will propagate.

Custom Autoclosable implementations
   
Autclosable interface has only one method , public void close().

class MyResourceHandler implements AutoCloseable{

@Override
public void close() throws Exception {
System.out.println("closing the resources");

}


}