Tuesday, May 24, 2016

Thread Safety

Multiple ways of achieving Java Thread Safety
Thread safety is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.
·         Synchronization is the easiest and most widely used tool for thread safety in java.
·         Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
·         Use of locks from java.util.concurrent.locks package.
·         Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.

·         Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

Daemon thread

By default, any thread we create ourselves is User thread. JVM shutdown as soon as it sees that all users thread are finished. It automatically shuts down the daemon thread too.
To create Daemon thread, we use Thread.setDaemon(true)

class JavaDaemonThread {
      
    public static void main(String[] args) throws InterruptedException {
        Thread dt = new Thread(new DaemonThread(), "dt");
        dt.setDaemon(true);
        dt.start();
        //continue program
        Thread.sleep(30000);
        System.out.println("Finishing program");
    }

}

class DaemonThread implements Runnable{

    @Override
    public void run() {
        while(true){
            processSomething();
        }
    }

    private void processSomething() {
        try {
            System.out.println("Processing daemon thread");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}

When we execute this program, JVM creates first user thread with main() function and then a daemon thread. When main function is finished, the program terminates and daemon thread is also shut down by JVM.

Output:
1
2
3
4
5
6
7
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Finishing program


Functional Interface in Java 8

An interface which includes an abstract method, default method , static method and can also override Object class methods.


public interface FunctionalInterface {

     // Only abstract method.
     void abc(Collection collection);

     // Functional interface can have more than one static or default methods.
     default void print() {
           System.out.println("This is default in Functional  Interface.");
     }
    
     //An interface can also have static helper methods from Java 8 onwards.
     static void abc() {
           System.out.println("Hey");
     }

     // And also can override methods of java.lang.Object
     @Override
     public String toString();

}

default() method in Java 8

Earlier interfaces have only methods without body/implementation. That means Classes implementing that interface must have implement that method.

From java8, with introduction of default keyword, one can give default implementation in interface itself which means if implementation is not there in concrete class, JVM will by default take default implementation.

public class DefaultMethod implements InterfaceA {

     public static void main(String[] args) {
           DefaultMethod df = new DefaultMethod();
           df.sayHi();
     }

     @Override
     public void saySomething() {
     }

}

interface InterfaceA {
     public void saySomething();

     /* Earlier we used to provide implementation in concrete class only.
      * By Adding the keyword default before the method’s access modifier, we do
      * not have to provide implementation for the method sayHi() in class
      * DefaultMethod.
      */

     default public void sayHi() {
           System.out.println("Hi frm InterfaceA. Not implemented in Class");
     }
}

Output:
Hi from InterfaceA. Not implemented in Class


What if there are two interfaces with same default method? How will concrete class call one interface default method?

public class DefaultMethod implements InterfaceA, InterfaceB {

     public static void main(String[] args) {
           DefaultMethod df = new DefaultMethod();
           df.sayHi();
     }

     @Override
     public void saySomething() {
     }
    
     /* Duplicate sayHi() in both Interface,
     To overcome from diamond problem,must override sayHi()*/
    
     @Override
     public void sayHi() {
           System.out.println("Implemented in main class DefaultMethod");
           InterfaceA.super.sayHi();
           InterfaceB.super.sayHi(); 
     }
}

interface InterfaceA {
     public void saySomething();

     /* Earlier we used to provide implementation in concrete class only.
      * By Adding the keyword default before the method’s access    modifier, we do not have to provide implementation for the method sayHi() in class DefaultMethod.
      */

     default public void sayHi() {
           System.out.println("Hi frm InterfaceA. Not implemented in Class");
     }
}

interface InterfaceB {
     default public void sayHi() {
           System.out.println("Hi frm InterfaceB. Not implemented in Class");
     }
}

Output:
Implemented in main class DefaultMethod
Hi frm InterfaceA. Not implemented in Class

Hi frm InterfaceB. Not implemented in Class

Monday, May 23, 2016

Exception Handling and some tricky problems based on that


      1)   As soon as JVM encounter return a; a is saved by JVM as 10 with the return statement. Since finally has a contract and it’ll always invoke, new a value would be 30 but JVM will return as 10 only.

public class ExceptionHandling1 {

      public static void main(String[] args) {
            System.out.println("Value of a :" + test());
      }

      private static int test() {
            int a = 10;
            try {
                  return a;
            } catch (Exception e) {
                  a = 20;
                  System.out.println("a in catch : " + a);
            } finally {
                  a = 30;
                  System.out.println("a in finally : " + a);
            }
            a = 40;
            System.out.println("a outside try-catch : " + a);
            return a;
      }
}

Output
a in finally : 30
Value of a :10
          
     2)     Return statements have overwriting behavior. The return statement in the try block will be overwritten by the return statement in finally block.
finally block if present will always be a deciding block for return value of method if return statement is present in finally block irrespective of return present in try and catch block.

public class Exceptionhandling2 {

      public static void main(String[] args) {
            System.out.println("Value of a :" + test());
      }

      @SuppressWarnings("finally")
      private static int test() {
            int a = 10;
            try {
                  return a;
            } catch (Exception e) {
                  a = 20;
                  System.out.println("a in catch : " + a);
                  return a;
            } finally {
                  a = 30;
                  System.out.println("a in finally : " + a);
                  return a;
            }
      }
}

      3)     Unreachable catch block for IOException. It is not allowed to catch a Checked Exception which is not thrown from try block except for class Exception and Throwable which has RuntimeException as the subclass for which decision is taken at the run time and not compile time.
When it comes to Checked Exception, Compiler checks from where it is thrown and since try is empty , it is showing compile time error

class ExceptionHandling3 {
     private static void test() {
            try { } catch (IOException e) {}
     }
}

We need to replace catch clause with throws IOException.

class ExceptionHandling3 {
      private static void test() throws IOException {
      }
}

     4)     Exception class can handle both checked and unchecked exception. Below code is perfectly valid because catch block catches Exception class and even though it is checked exception, Compiler doesn't complain because the compiler is not sure that catch block is written to handle checked exception or unchecked(Runtime) exception as Exception class can handle both so above code is perfectly valid.

 class ExceptionExample31 {
      private static void test() {
            try {
            } catch (Exception e) {
            }
      }
}

Below code is perfectly valid and the compiler doesn't complain because when you catch the Unchecked exception that is either RuntimeException or Error or any subclass of it then the compiler doesn't check what is written in try block because this Exception/Error can occur at run time, so for compilation it is perfectly valid call.

class ExceptionExample32 {
      private static void test() {
            try {
            } catch (NullPointerException e) {
            }
      }
}

     5)     Exception is a checked Exception thus it must be handled either by try-catch block or using throws keyword.

 class ExceptionHandling {
      public static void main(String[] args) {
            test();
      }

      private static void test() {
            throw new Exception();

      }
}


Output:  Compile Time Error : Unhandled exception type Exception
Exception class is checked exception and when some method throw CHECKED exception, then it requires a handler for checked exception or the method itself throws the exception claiming as I am not going to handle exception and whoever calls me need to be handled. 
So test() method here doesn't provided a handler for it nor it throws Exception as  indication to compiler that it is not going to handle it that is why it is compile time error.
     
     6)     Output:  true

Why control never reached to line "Outside try-catch-finally" because in try block JVM encountered return statement, which is indication for JVM to return from here, but as a 
contract to execute finally block always (except in few conditions), finally block get executed which doesn't contain any statement, so control returned from finally back to try block and method returned from there without executing statements after finally block.
 class ExceptionExample {

     public static final void main(String[] args) {
           System.out.println(test());
     }

     private static boolean test() {
           boolean flag = false;

           try {
                return true;
           } catch (Exception e) {
           } finally {
           }

           System.out.println("Outside try-catch-finally");
           return flag;
     }
}
     
     7)     Unreachable catch block for FileNotFoundException.
catch() must caught subclass Exception first and then move to superclass.

 class ExceptionHandler{
     public static void main(String[] args) {
           try {
                // do risky IO things
                } catch (IOException e) {
                // handle general IOExceptions
                } catch (FileNotFoundException ex) {
                // handle just FileNotFoundException
                }
     }
}

Facts about Exception handling:

1) All non-RuntimeExceptions are considered "checked" exceptions because the compiler checks to be certain you've acknowledged that "bad things could happen here."

2) Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.

3) Unchecked Exceptions are exempted i.e. they need not be handled.