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.

ThreadPoolExecutor Methods

Sr.No.Method & Description
1protected void afterExecute(Runnable r, Throwable t)Method invoked upon completion of execution of the given Runnable.
2void 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.
3boolean 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.
4boolean 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.
5protected void beforeExecute(Thread t, Runnable r)Method invoked prior to executing the given Runnable in the given thread.
6void execute(Runnable command)Executes the given task sometime in the future.
7protected void finalize()Invokes shutdown when this executor is no longer referenced and it has no threads.
8int getActiveCount()Returns the approximate number of threads that are actively executing tasks.
9long getCompletedTaskCount()Returns the approximate total number of tasks that have completed execution.
10int getCorePoolSize()Returns the core number of threads.
11long 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.
12int getLargestPoolSize()Returns the largest number of threads that have ever simultaneously been in the pool.
13int getMaximumPoolSize()Returns the maximum allowed number of threads.
14int getPoolSize()Returns the current number of threads in the pool.
15BlockingQueue getQueue()Returns the task queue used by this executor.
15RejectedExecutionHandler getRejectedExecutionHandler()Returns the current handler for unexecutable tasks.
16long getTaskCount()Returns the approximate total number of tasks that have ever been scheduled for execution.
17ThreadFactory getThreadFactory()Returns the thread factory used to create new threads.
18boolean isShutdown()Returns true if this executor has been shut down.
19boolean isTerminated()Returns true if all tasks have completed following shut down.
20boolean isTerminating()Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated.
21int prestartAllCoreThreads()Starts all core threads, causing them to idly wait for work.
22boolean prestartCoreThread()Starts a core thread, causing it to idly wait for work.
23void purge()Tries to remove from the work queue all Future tasks that have been cancelled.
24boolean 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.
25void setCorePoolSize(int corePoolSize)Sets the core number of threads.
26void setKeepAliveTime(long time, TimeUnit unit)Sets the time limit for which threads may remain idle before being terminated.
27void setMaximumPoolSize(int maximumPoolSize)Sets the maximum allowed number of threads.
28void setRejectedExecutionHandler(RejectedExecutionHandler handler)Sets a new handler for unexecutable tasks.
29void setThreadFactory(ThreadFactory threadFactory)Sets the thread factory used to create new threads.
30void shutdown()Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
31List<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.
32protected void terminated()Method invoked when the Executor has terminated.
33String toString()Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.

Example

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.

Output

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *