ThreadPoolExecutor(C) in JAVA

  • ThreadPoolExecutor class used for executing a group of threads by using the Executors(I) factory methods.
  • It is a known implementation of Executor(I),ExecutorService(I) and it allows callble or runnable objects as params.
  • It creates the thread objects and executes it and destirys it by using of varoius methods in ThreadPoolExecutor class.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

  • getcurrentPoolSize() ==> gives current pool elemnts size
  • getCorepoolSize()     ====> Intial size i.e no of Queue elemnts.
  • getMaxPoolSize()     =====> Large size  i.e MAX elements.
  • When the new task is submitted to execute() and less than getCuurentSize()   a new thread is created.
  • if more than coresize and less than max size then a thread created in the queue(synchronus queue,LinkedBlockingqueu,ArrayblockingQueue).

A detailed desc is below.

 

Source:

package com.practice.thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Thread_Creation implements Runnable{

public String stringThread=null;

public Thread_Creation(String stringThread) {
super();
this.stringThread = stringThread;
}

public String getStringThread() {
return stringThread;
}

public void setStringThread(String stringThread) {
this.stringThread = stringThread;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.stringThread.toString();
}

@Override
public void run() {
// TODO Auto-generated method stub
// default-method in runnable(I)

System.out.println(“Start”);
System.out.println(Thread.currentThread().getName()+stringThread);
logicMethod();
System.out.println(“stop”);
System.out.println(Thread.currentThread().getName()+stringThread);

}

private void logicMethod() {
// TODO Auto-generated method stub
//We are simply sleep it for 5 sec.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class Simple_Thread{
public static void main(String[] args) {
Runnable runnable=null;
ExecutorService executorService=Executors.newFixedThreadPool(5);
//It will creates the new threads of 15.
//One dis-advantage is if num is big it get overloaded.

for(int i=0;i<10;i++){
runnable=new Thread_Creation(” “+i);
executorService.execute(runnable);
}
}
}

 

Start
Start
Start
Start
pool-1-thread-1 0
Start
pool-1-thread-3 2
pool-1-thread-5 4
pool-1-thread-2 1
pool-1-thread-4 3
stop
stop
stop
stop
pool-1-thread-3 2
stop
pool-1-thread-5 4
Start
pool-1-thread-3 5
Start
pool-1-thread-5 6
pool-1-thread-2 1
pool-1-thread-4 3
pool-1-thread-1 0
Start
Start
pool-1-thread-4 8
Start
pool-1-thread-2 7
pool-1-thread-1 9
stop
stop
pool-1-thread-5 6
pool-1-thread-3 5
stop
pool-1-thread-1 9
stop
pool-1-thread-2 7
stop
pool-1-thread-4 8

 

package com.practice.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Rejected_Threads implements RejectedExecutionHandler{

@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor arg1) {
// TODO Auto-generated method stub
System.out.println(runnable+”got rejected:”);
}

}

class Mainlogic_Thread implements Runnable{

public ThreadPoolExecutor executor;
public boolean run=true;
public int seconds;

public Mainlogic_Thread(ThreadPoolExecutor threadpoolObject, int seconds) {
super();
this.executor = threadpoolObject;
this.seconds = seconds;
}

public void shutdown(){
this.run=false;
}

@Override
public void run() {
// TODO Auto-generated method stub
while(run){
System.out.println(
String.format(“[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s”,
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
public class Thread_pool_executer {
public static void main(String[] args) throws InterruptedException {
Rejected_Threads rejected_Threads=new Rejected_Threads();
ThreadFactory threadFactory=Executors.defaultThreadFactory();
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(2, 4, 10,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(2),threadFactory,rejected_Threads);

//Notice that while initializing the ThreadPoolExecutor, we are keeping initial pool
//size as 2, maximum pool size to 4 and work queue size as 2. So if there are 4
//running tasks and more tasks are submitted, the work queue will hold only 2 of
//them and rest of them will be handled by RejectedExecutionHandlerImpl.

Mainlogic_Thread mainlogic_Thread=new Mainlogic_Thread(threadPoolExecutor, 3);
Thread thread=new Thread(mainlogic_Thread);
thread.start();

for(int i=0; i<10; i++){
threadPoolExecutor.execute(new Thread_Creation(“cmd”+i));
}

System.out.println(threadPoolExecutor.getCorePoolSize());
System.out.println(threadPoolExecutor.getMaximumPoolSize());

Thread.sleep(30000);
//shut down the pool
threadPoolExecutor.shutdown();
//It won’t execute any pending taks if we call shutdown()
//shut down the monitor thread
//If shout down is called it goes to rejection if we try to put it in executor queue
threadPoolExecutor.execute(new Thread_Creation(“nene”+2));
Thread.sleep(5000);
mainlogic_Thread.shutdown();

}
}

 

Start
cmd6got rejected:
pool-1-thread-1cmd0
cmd7got rejected:
Start
cmd8got rejected:
pool-1-thread-2cmd1
cmd9got rejected:
2
4
Start
pool-1-thread-3cmd4
Start
pool-1-thread-4cmd5
[monitor] [0/2] Active: 0, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
stop
stop
pool-1-thread-2cmd1
pool-1-thread-1cmd0
Start
pool-1-thread-2cmd2
Start
pool-1-thread-1cmd3
stop
stop
pool-1-thread-3cmd4
pool-1-thread-4cmd5
stop
stop
pool-1-thread-1cmd3
pool-1-thread-2cmd2
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
nene2got rejected:
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s