Tuesday, December 29, 2015

Callable Interface in Java

Callable Interface in Java

1) Runnable interface is older than Callable, there from JDK 1.0, while Callable is added on Java 5.0.

2) Runnable interface has run() method to define task while Callable interface uses call() method for task definition.

3) run() method does not return any value, it's return type is void while call method returns value. Callable interface is a generic parameterized interface and Type of value is provided, when instance of Callable implementation is created.

4) Another difference on run and call method is that run method can not throw checked exception, while call method can throw checked exception in Java.

java.util.concurrent.Callable has been introduced in JDK 5 . Callable is a thread that returns the result. There is a method call() in Callable interface that must be overridden for computation task.

To run Callable, submit() method of ExecutorService is used. ExecutorService also provides invokeAll() and invokeAny () method to run Callable threads.

To fetch the result of call() method of Callable interface, java provides Future class. ExecutorService.submit() method returns Future instance and then get() method of Future, returns the result of call() method of Callable..

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableDemo{
            public static void main(String[] args) throws InterruptedException,              ExecutionException {
                        ExecutorService service =Executors.newSingleThreadExecutor();
                        SumTask st=new SumTask(5);
                        Future<Integer> future=service.submit(st);
                        Integer result=future.get();
                        System.out.println(result);
            }
           
}

 class SumTask implements Callable<Integer>{

            private int num;
            public SumTask(int num) {
                        this.num=num;
            }

            @Override
            public Integer call() throws Exception {
                        int result = 0;
                        for(int i=1;i<=num;i++){
                                    result+=i;
                        }
                        return result;
            }
}


Output :

15

Monday, December 28, 2015

Sleep and Wait Method

Difference between sleep() and wait()

Sleep()
Wait()
     1)     Static method of Thread class
     1)     Method of Object Class
     2)     Thread keeps the lock it has acquired

synchronized(LOCK) {
    Thread.sleep(1000); // LOCK is held
}

     2)     Call to wait() releases the acquired lock

synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
}

     3)     It is called on Thread class
     3)     Wait is called on an object, not a thread
     4)     The Object need not to be in synchronized block
     4)     Before calling wait() , the object should be in synchronized , means the object should be in synchronized block.
     5)    Wake-up, when time expires or interrupt() called on the thread.
     5)   Wake-up when notify(),notifyAll() called from object
     6)     Usage : for time-synchronization               
     6)     Usage : for multi-thread communication



Thread Interaction using wait and notify- Producer and Consumer


Wait() method can be used for multithread-synchronization i.e. wait() method is used for inter-thread communication.

When wait() called, Current thread relinquishes the lock and give to another Thread and comes into play when another thread notify the current thread to continue

wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:

Object mon = ...;
synchronized (mon) {
    mon.wait();
}

At this point the currently executing thread waits and releases the monitor. Another thread may do

synchronized (mon) { mon.notify(); }

(On the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.

public class ProducerConsumerWN {
    public static void main(String[] args) throws InterruptedException {
        
          final Processor1 processor=new Processor1();
          Thread t1 = new Thread(new Runnable() {
               @Override
               public void run() {
                    try {
                          processor.producer();
                    } catch (InterruptedException e) {
                          e.printStackTrace();
                    }
               }

          });

          Thread t2 = new Thread(new Runnable() {
               @Override
               public void run() {
                    try {
                          processor.consumer();
                    } catch (InterruptedException e) {
                          e.printStackTrace();
                    }
               }

          });
          t1.start();
          t2.start();
          t1.join();
          t2.join();
    }
}

class Processor1 {
     public void producer() throws InterruptedException {
        synchronized (this) {
             System.out.println("Lock acquired by" + Thread.currentThread().getName());
             System.out.println("Producer Thread running");
             this.wait();
             System.out.println("Resumed");
             System.out.println("Lock released by" + Thread.currentThread().getName());
        }
  }
     public void consumer() throws InterruptedException {
        Scanner scan = new Scanner(System.in);
        Thread.sleep(2000);
        synchronized (this) {
             System.out.println("Lock acquired by"+ Thread.currentThread().getName());
             System.out.println("Waiting for return hit");
             scan.nextLine();
             this.notify();
             System.out.println("Lock released by" + Thread.currentThread().getName());
             Thread.sleep(5000);
        }
  }
}

Output:
Lock acquired byThread-0
Producer Thread running
Lock acquired byThread-1
Waiting for return hit

Lock released byThread-1
5 sec wait
Resumed
Lock released byThread-0


EXAMPLE 2- WHERE RESULT PRINTS ONLY WHEN CALCULATION COMPLETES



package com.java5.executor;

public class Calculation {

     public static void main(String[] args) throws InterruptedException {
           ThreadA threadA = new ThreadA();
           threadA.start();
           /*we need to put a lock here and wake up only when
            * below calculation completes than means below thread
            * notify*/
           synchronized(threadA) {
                System.out.println("Putting thread in wait so as to complete calculation");
                threadA.wait();
                System.out.println("Total is " + threadA.total);
           }
     }
}

class ThreadA extends Thread {
     long total=1;
     public void run() {
           synchronized(this){
           for (int i = 1; i < 20; i++) {
                total = total * i;
           }
           this.notify();
      }
     }
}


Output

Putting thread in wait so as to complete calculation

Total is 121645100408832000

References

http://howtodoinjava.com/core-java/multi-threading/how-to-work-with-wait-notify-and-notifyall-in-java/
http://javarevisited.blogspot.in/2013/12/inter-thread-communication-in-java-wait-notify-example.html