ThreadPool Class

Used to spawn threads and execute tasks. Instances of this class should override the process() method which is called by individual threads. Objects (e.g. data) are added to a queue via the add() method. Individual threads wait for data to be added to the queue. As new data is added, it is assigned to a thread to process. The thread, in turn, calls the process() method. The ThreadPool will run indefinitely, unless the done() method is called. The join() method can be used to join the ThreadPool to the caller's thread. Example:

      //Instantiate thread pool
        int numThreads = 2;
        ThreadPool pool = new ThreadPool(numThreads){
            public void process(Object obj){
                //Do something!
            }
        };

      //Start the thread
        pool.start();


      //Add tiles to the pool
        for (int i : new int[]{1,2,3,4,5,6,7,8,9,10}){
            pool.add(i);
        }


      //Notify the pool that we have finished added records
        pool.done();


      //Wait for threads to finish
        pool.join();
     

Constructors

ThreadPool( int numThreads, Integer maxPoolSize )
ThreadPool( int numThreads )

Public Methods

start( ) returns ThreadPool
Used to initialize threads in the pool
process( Object obj ) returns void
Called whenever a thread gets an object to process
exit( ) returns void
Called when a thread is being disposed
get( String key ) returns Object
Returns a variable for an individual thread
get( String key, Setter setter ) returns Object
Returns a variable associated with an individual thread
keyThe name of the variable
setterOptional. Used to generate a value if the value has not been set. The following example shows how to call the get method with a setter as a lamba expression to return a new database connection:
        Connection conn = (Connection) get("conn", () -> {
            return database.getConnection();
        });    
set( String key, Object value ) returns void
Used to set a variable for an individual thread
add( Object object ) returns int
Used to add an object to the pool to process
getActiveThreadCount( ) returns int
Returns the number of active threads in the pool
getQueue( ) returns List
Returns a handle to the job queue. Use with care. Be sure to add a synchronized block when processing or iterating through items in the queue.
done( ) returns void
Used to notify the threads that we are done adding objects to the pool and to exit when ready
join( ) returns void
Used to wait for threads to complete

Public Classes