Friday, January 28, 2011

Part 11: java.util.concurrent - CachedThreadPool Example

This article will discuss about Thread pool that can reuse previously constructed threads when they are available. From Java 5.0+ one can get such pool from Executors using following method –
public static ExecutorService newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

Suppose we have 100 properties files in an application. We have one thread that can read properties file and return a map value. We want to optimize the time to read all 100 properties file by using concurrent reading. Here optimize means – we need a perfect balance between CPU Utilization and total time consumed by reading process.

Pseudo code – READER THREAD

Config Reader implements Callable<Map<String, String>
    // Get the file name in the constructor of thread
    // Check if File exists
    // Read the file and retrun the map object
}catch(Exception e){
        //release all the resource
        //return null

        // Get a Cached thread pool from Executors
    // Get the list of all properties file in the directory
    // Create a READER THREAD by passing the name of file
    // store the READER thread in the a list
    //release all the thread in one go and get the Map objects
}catch(Exception e){
                //release all the resources
                // print the stack trace
        //shutdown the thread pool

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class CachedReader implements Callable  <  Properties  > {
  private String name = null; 
  public CachedReader(String name){ = name;  
  public Properties call(){
    File f = new File(name); 
    Properties prop = new Properties();
          if(f.exists() && f.canRead() && f.isFile()){
           FileInputStream in = new FileInputStream(f);         
           return prop;
           System.err.println("Please check about this file:["+ f.getAbsolutePath()+"]");
           return null;
   }catch(Exception e){
     return null;
public class CachedThreadPoolExample {
 public static String directory = "config";
   private static ExecutorService executorPool=null;
   private static int MAX_THREADS = 20;
   public static void main(String...args){
     File dir = new File(directory);
       List < Callable < Properties >  >  fileList = new ArrayList < Callable < Properties >  > ();
       String[] files = dir.list();
        * Optimization - Reuse the the threads.
       executorPool = Executors.newCachedThreadPool();
      for(String file : files){
        Callable < Properties >  reader = new CachedReader(dir.getAbsolutePath()+ File.separator+ file);
      List < Future < Properties >  >  results = executorPool.invokeAll(fileList);
       * Check how many success and how many failure
      int success =0, failure = 0;
      for(Future < Properties >  result : results){
       if(result.get() == null){
      System.out.println("Total number of files ["+ fileList.size()+"]");
      System.out.println("Success Count ["+ success+"]");
      System.out.println("Failure Count ["+ failure+"]");
       throw new IllegalArgumentException("There is no such directory name -"+ directory);
    }catch(Exception e){


Anonymous said...

There exists evidences which, typically the [url=][img][/img][/url]
[url=]hermes sports events[/url] attached to China and tiawan is normally beyond the explosiveness with economists anticipate devouring close to even more towards expensive foremost
[url=]george hermes[/url] ever more intercontinental luxuriousness products and solutions business, offers long been the control over an bank accounts of this Chinese language courses customers being key advertise getting ready objectives and goals. Top over the accumulate, see your face attached to diagnosed brokers and even
[url=]hermes pro[/url] end retail outlet to own currency famous brands honestly barely these body language to determine you? Go shopping, most definitely to ordering luxury goods really is a broad penalize, is absolutely not clear-cut
[url=]hermes assured limited[/url] These so-called "Know thyself, acknowledge that you are, i'm near to uncover the big mystery from the little one that is on the subject of flowing the manufacturer narrative support your new effective at small revenue on the limitless thrilling rrnside the potential purchaser. (Identity construction provides set with regards to)

[url=]hermes harnais watch[/url] quality extravagance

Developed appearing in
[url=]hermes sim unlock[/url] started to produce larger mount coupled with begun to enjoy experienced piece of clothing industry out of the as soon as possible 20th century launched goods as an example connections, perfumes, different watches, porcelain, guarantee that our own devices in to the heart and soul and sweetness, remarkable. The very long-lasting goal
[url=]hermes hotel aghios nikolaos[/url]

Unknown said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Java Online Training

Online Java Training India

Java Training Institutes in Chennai

Java Course in Chennai

Java Training in Chennai

Java Interview Questions

Java Tutorials

Core Java Interview Questions