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
1

protected void afterExecute(Runnable r, Throwable t)

Method invoked upon completion of execution of the given Runnable.

2

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.

3

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.

4

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.

5

protected void beforeExecute(Thread t, Runnable r)

Method invoked prior to executing the given Runnable in the given thread.

6

void execute(Runnable command)

Executes the given task sometime in the future.

7

protected void finalize()

Invokes shutdown when this executor is no longer referenced and it has no threads.

8

int getActiveCount()

Returns the approximate number of threads that are actively executing tasks.

9

long getCompletedTaskCount()

Returns the approximate total number of tasks that have completed execution.

10

int getCorePoolSize()

Returns the core number of threads.

11

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.

12

int getLargestPoolSize()

Returns the largest number of threads that have ever simultaneously been in the pool.

13

int getMaximumPoolSize()

Returns the maximum allowed number of threads.

14

int getPoolSize()

Returns the current number of threads in the pool.

15

BlockingQueue getQueue()

Returns the task queue used by this executor.

15

RejectedExecutionHandler getRejectedExecutionHandler()

Returns the current handler for unexecutable tasks.

16

long getTaskCount()

Returns the approximate total number of tasks that have ever been scheduled for execution.

17

ThreadFactory getThreadFactory()

Returns the thread factory used to create new threads.

18

boolean isShutdown()

Returns true if this executor has been shut down.

19

boolean isTerminated()

Returns true if all tasks have completed following shut down.

20

boolean isTerminating()

Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated.

21

int prestartAllCoreThreads()

Starts all core threads, causing them to idly wait for work.

22

boolean prestartCoreThread()

Starts a core thread, causing it to idly wait for work.

23

void purge()

Tries to remove from the work queue all Future tasks that have been cancelled.

24

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.

25

void setCorePoolSize(int corePoolSize)

Sets the core number of threads.

26

void setKeepAliveTime(long time, TimeUnit unit)

Sets the time limit for which threads may remain idle before being terminated.

27

void setMaximumPoolSize(int maximumPoolSize)

Sets the maximum allowed number of threads.

28

void setRejectedExecutionHandler(RejectedExecutionHandler handler)

Sets a new handler for unexecutable tasks.

29

void setThreadFactory(ThreadFactory threadFactory)

Sets the thread factory used to create new threads.

30

void shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

31

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.

32

protected void terminated()

Method invoked when the Executor has terminated.

33

String 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
Advertisements