Part 12: java. util. concurrent: SingleThreadPool Example

Source: Internet
Author: User

This article will discuss about Thread pool that uses single thread to execute tasks. From Java 5.0 + one can get such pool from Executors using following method-
Public static ExecutorService newSingleThreadExecutor ()
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks .) tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. unlike the otherwise equivalent newFixedThreadPool (1) the returned executor is guaranteed not to be rewritable able to use additional threads.

 

Example-
Suppose we have 100 properties files in an application. We have one thread that can read properties file and return a map value.

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 Single 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 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
}

Package com. jovialjava. blog. threads;

Import java. io. File;
Import java. io. FileInputStream;
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 SingleReader implements Callable <Properties> {

Private String name = null;

Public SingleReader (String name ){
This. name = name;
}

Public Properties call (){
Try {
File f = new File (name );
Properties prop = new Properties ();
If (f. exists () & f. canRead () & f. isFile ()){
FileInputStream in = new FileInputStream (f );
Prop. load (in );
Return prop;
} Else {
System. err. println ("Please check about this file: [" + f. getAbsolutePath () + "]");
Return null;
}
} Catch (Exception e ){
E. printStackTrace ();
Return null;
}
}
}

Public class SingleThreadPoolExample {
Public static String directory = "config ";
Private static ExecutorService executorPool = null;

Public static void main (String args ){
Try {
File dir = new File (directory );
If (dir. isDirectory ()){
List <Callable <Properties> fileList = new ArrayList <Callable <Properties> ();
String [] files = dir. list ();
/**
* Optimization-Single thread executor.
*/
ExecutorPool = Executors. newSingleThreadExecutor ();

For (String file: files ){
Callable <Properties> reader = new SingleReader (dir. getAbsolutePath () + File. separator + file );
FileList. add (reader );
}
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 ){
Failure ++;
} Else {
Success ++;
}
}
System. out. println ("Total number of files [" + fileList. size () + "]");
System. out. println ("Success Count [" + success + "]");
System. out. println ("Failure Count [" + failure + "]");
} Else {
Throw new IllegalArgumentException ("There is no such directory name-" + directory );
}
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
If (executorPool! = Null ){
ExecutorPool. shutdown ();
}
}
}

}


Author: silence is gold

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.