This  article will discuss about Thread pool with fixed number of thread.  From Java 5.0+ one can get such pool from Executors using following  method –
public static ExecutorService 
               newFixedThreadPool(int nThreads)
    Creates  a thread pool that reuses a fixed number of threads operating off a  shared unbounded queue. At any point, at most nThreads threads will be  active processing tasks. If additional tasks are submitted when all  threads are active, they will wait in the queue until a thread is  available. If any thread terminates due to a failure during execution  prior to shutdown, a new one will take its place if needed to execute  subsequent tasks. The threads in the pool will exist until it is  explicitly shutdown.
 
Example-
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 10 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>
try{
    // 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
}
 
Main THREAD-
        // Get a fixed thread pool from Executors
 try{
    // 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
}finally{
        //shutdown the thread pool
}posted on 2012-08-06 10:43 
ゞ沉默是金ゞ 阅读(928) 
评论(0)  编辑  收藏  所属分类: 
Java SE