ThreadPoolExecutor Class

java.util.concurrent.ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.
protected void afterExecute(Runnable r, Throwable t)
Method invoked upon completion of execution of the given Runnable.
void allowCoreThreadTimeOut(boolean value)
Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.
boolean	allowsCoreThreadTimeOut()
Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive.
boolean	awaitTermination(long timeout, TimeUnit unit)
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
protected void beforeExecute(Thread t, Runnable r)
Method invoked prior to executing the given Runnable in the given thread.
void execute(Runnable command)
Executes the given task sometime in the future.
protected void finalize()
Invokes shutdown when this executor is no longer referenced and it has no threads.
int	getActiveCount()
Returns the approximate number of threads that are actively executing tasks.
long getCompletedTaskCount()
Returns the approximate total number of tasks that have completed execution.
int	getCorePoolSize()
Returns the core number of threads.
long	getKeepAliveTime(TimeUnit unit)
Returns the thread keep-alive time, which is the amount of time that threads in excess of the core pool size may remain idle before being terminated.
int	getLargestPoolSize()
Returns the largest number of threads that have ever simultaneously been in the pool.
int	getMaximumPoolSize()
Returns the maximum allowed number of threads.
int	getPoolSize()
Returns the current number of threads in the pool.
BlockingQueue getQueue()
Returns the task queue used by this executor.
RejectedExecutionHandler getRejectedExecutionHandler()
Returns the current handler for unexecutable tasks.
long getTaskCount()
Returns the approximate total number of tasks that have ever been scheduled for execution.
ThreadFactory getThreadFactory()
Returns the thread factory used to create new threads.
boolean	isShutdown()
Returns true if this executor has been shut down.
boolean	isTerminated()
Returns true if all tasks have completed following shut down.
boolean	isTerminating()
Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated.
int	prestartAllCoreThreads()
Starts all core threads, causing them to idly wait for work.
boolean	prestartCoreThread()
Starts a core thread, causing it to idly wait for work.
void purge()
Tries to remove from the work queue all Future tasks that have been cancelled.
boolean	remove(Runnable task)
Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.
void setCorePoolSize(int corePoolSize)
Sets the core number of threads.
void setKeepAliveTime(long time, TimeUnit unit)
Sets the time limit for which threads may remain idle before being terminated.
void setMaximumPoolSize(int maximumPoolSize)
Sets the maximum allowed number of threads.
void setRejectedExecutionHandler(RejectedExecutionHandler handler)
Sets a new handler for unexecutable tasks.
void setThreadFactory(ThreadFactory threadFactory)
Sets the thread factory used to create new threads.
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
List<Runnable> shutdownNow()
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
protected void terminated()
Method invoked when the Executor has terminated.
String toString()
Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.
The following TestThread program shows usage of ThreadPoolExecutor interface in thread based environment.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {
	
   public static void main(final String[] arguments) throws InterruptedException {
      ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();

      //Stats before tasks execution
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.submit(new Task());
      executor.submit(new Task());

      //Stats after tasks execution
      System.out.println("Core threads: " + executor.getCorePoolSize());
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.shutdown();
   }  

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task! Thread Name: " +
               Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed! Thread Name: " +
               Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}
This will produce the following result.
Largest executions: 0
Maximum allowed threads: 2147483647
Current threads in pool: 0
Currently executing threads: 0
Total number of threads(ever scheduled): 0
Core threads: 0
Largest executions: 2
Maximum allowed threads: 2147483647
Current threads in pool: 2
Currently executing threads: 2
Total number of threads(ever scheduled): 2
Running Task! Thread Name: pool-1-thread-2
Running Task! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-2


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page