Wednesday, April 6, 2016

A launcher to run multiple Applications in same JVM instance

Each single java application runs in its own JVM instance.
We launch a java application by "java" command and it creates a separate JVM instance to run this application.
If we want to run separate applications on same JVM instances we can run them in different threads from a common launcher.
In this example, we have a launcher that accepts different application names and run in different threads.

public class Launcher {
  public static void main(String[] args) throws Exception {
    for (int i = 0; i<args.length; i++) {
      final Class clazz = Class.forName(args[i]);
      new Thread(new Runnable() {
        @Override
        public void run() {
           try{
             Method main = clazz.getMethod("main", String[].class);
             main.invoke(null, new Object[]{});
           } catch(Exception e) {
             // improper exception handling - just to keep it simple
           }
        }
      }).start();
    }
  }
}
Calling it like
  java -cp <classpath for all applications!> Launcher com.example.App1 com.example.App2

Tuesday, April 5, 2016

Java and pass by value

In programming language method arguments are passed by two ways :

1. Pass By value : A copy of the argument is stored in the memory location allocated for formal parameters.In this case any changes made inside method will not affect the value of the argument in the calling method.

2. pass by reference : the memory address of the argument is passed to the method, making the formal parameter an alias for the argument. This means that changes made to the formal parameter inside the method will be reflected in the value of the argument when control is returned to the calling function.


We are clear about java's pass by value behavior for primitive types. But most of us say that java uses pass by reference for object arguments and here we go wrong.
In case of object as an argument, a copy of the object reference is passed to the method(hence this copy of reference point to the same object).

Points to note :
1. Any changes made on the object reference in a method will affect the original object, since it points to the object.
2. Inside a method , if the reference is assigned to a new object, there will not be any change in the original object.

class Cat{
private String name;

public Cat(String name) {
this.name=name;
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

class Test {


 public void doStuff(Cat cat){
    cat=new Cat("cat2");

     }

     public void doStuff1(Cat cat){
    cat.setName("new name");

     }

public static void main(String[] args) {

     Cat cat=new Cat("cat1");
     TestMain test=new TestMain();
     test.doStuff(cat);
     System.out.println(cat.getName()); //will print cat1

     test.doStuff1(cat);
     System.out.println(cat.getName()); //will print new name



}

}

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