Google

Jul 25, 2013

Core Java Executor Service (Thread Pool) Tutorial



Here is a simple code that uses a thread pool of 3 threads to output a list. A stop watch is used to measure the time.

package com.mycompany.app8;

import java.util.Arrays;
import java.util.List;

public class ExecutorServiceTest
{
    
    public static void main(String[] args)
    {
        MyBusinessService bs = new MyBusinessServiceImpl();
        
        for (int i = 0; i < 3; i++)
        {
            List<String> items = Arrays.asList("Java", "JEE", "JDBC", "EJB");
            bs.process(items);
        }
        
    }  
}


package com.mycompany.app8;

import java.util.List;

public interface MyBusinessService
{
    abstract void process(List<String> values);
    
    abstract void shutdownAndAwaitTermination();
}


package com.mycompany.app8;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.camel.util.StopWatch;

public class MyBusinessServiceImpl implements MyBusinessService
{
    
    private ExecutorService threadPool;
    
    public MyBusinessServiceImpl()
    {
        init();
    }
    
    void init()
    {
        threadPool = Executors.newFixedThreadPool(3);
    }
    
    public void process(final List<String> values)
    {
        threadPool.execute(new Runnable()
        {
            
            public void run()
            {
                StopWatch watch = new StopWatch();
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName + " --> " + values);
                System.out.println(threadName + " --> elapse time:" + watch.stop());
                
            }
            
        });
    }
    
}

The output will be:

pool-1-thread-2 --> [Java, JEE, JDBC, EJB]
pool-1-thread-3 --> [Java, JEE, JDBC, EJB]
pool-1-thread-3 --> elapse time:0
pool-1-thread-1 --> [Java, JEE, JDBC, EJB]
pool-1-thread-2 --> elapse time:0
pool-1-thread-1 --> elapse time:0


Q. what is missing from the above?
A. The thread pool does not shut down. The shut down logic can be added as shown below.


Add the following method to MyBusinessServiceImpl class.

 public void shutdownAndAwaitTermination()
    {
        final int timeout = 60;
        final TimeUnit timeoutUnit = TimeUnit.SECONDS;
        threadPool.shutdown(); // Disable new tasks from being submitted
        try
        {
            // Wait a while for existing tasks to terminate
            if (!threadPool.awaitTermination(timeout, timeoutUnit))
            {
                threadPool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!threadPool.awaitTermination(timeout, timeoutUnit))
                {
                    System.out.println("MyBusinessServicee did not terminate");
                }
            }
        }
        catch (InterruptedException ie)
        {
            // (Re-)Cancel if current thread also interrupted
            threadPool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }
    

The ExecutionServiceTest will invoke this method.

package com.mycompany.app8;

import java.util.Arrays;
import java.util.List;

public class ExecutorServiceTest
{ 
    public static void main(String[] args)
    {
        MyBusinessService bs = new MyBusinessServiceImpl();
        
        for (int i = 0; i < 3; i++)
        {
            List<String> items = Arrays.asList("Java", "JEE", "JDBC", "EJB");
            bs.process(items);
        }
        
        bs.shutdownAndAwaitTermination();
    } 
}

Note: The Google library has a StopWatch class (com.google.common.base.Stopwatch) as well.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home