Wednesday, April 14, 2010

Java Executor Service and Future !!!


Some jobs can be passed to another thread/pool and can be called with a given timeout value.
By the way your application business logic can continue its execution without waiting longer than expected or hanging.
Here is the task is "Callable c" and given timeout is 2000 millisecond. "future.get". So we will get a TimeoutException.

You can easily test it by running.
I have tried to simulate some blocking method with Thread.sleep ().You can replace it with your own code (exm:socket.read ()).


In the below example timeout is 2 seconds and operation takes 3 seconds.So code will get timeoutException.If you decrease the timeout will get a return object called ReturnObject.

import java.util.concurrent.*;

public class FutureTest {
    private static int nThreads = 20;

    public static void main(String[] args) {
        LinkedBlockingQueue taskQueue = new LinkedBlockingQueue(nThreads);

        ExecutorService executorService = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS, taskQueue);


        Callable c = new Callable() {
            public Object call() throws Exception {
               Thread.sleep(3000);
               ReturnObject rt =  new ReturnObject();
                rt.setReturnName("serkan sunel");
                return rt;
            }
        };

        Future future = executorService.submit(c);
        try {
            Object returnObj = future.get(2000, TimeUnit.MILLISECONDS);
            System.out.println("returned :" + returnObj);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }
}





No comments:

Post a Comment