Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday 13 June 2020

ThreadPoolExecuter in java

Hello Friends,

If you are working with thread and want to use more better thread so know about ThreadpoolExecuter.


Why you need threadpool?
If you create any simple application and create some of runnable objets and create corresponding thread and execute them. The creating and executing every thread every time this is very complex work and reduce the app performance also.

How to work threadpool ?
Threadpool is collection of pre-initialised thread. Generally the size if the collection is fixed but it is not mandatory. Its facilitated to execute N number of task using the same thread and task need to wait in queue like FIFO. When any task is completed of execution i can pickup the new task from the queue and start execution.

See image to understand



What is threadpoolExecuter?
Java 5 is introducing Executer  interface and ExecuterService. ThreadPoolExecuter is class and implement these both interfaces.
ThreadPoolExecuter is separate the task creation and execution. In ThreadPoolExecuter  you have can implement runnable object and send them to executer. It's responsible for execution, instantiation and running with particular thread.

How to create ThreadPoolExecuter?
We can create 5 types-:

Fixed thread pool executer: Create thread pool that reuse fixed number of thread to execute any number of thread. When additional task are submitted when all thread are active, they will wait in queue until thread  available its is the best example for real-life use.


  ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newFixedThreadPool(10);

Cached thread pool executer: Create a thread pool that is create new thread as needed but reuse perviously constructed thread if they are available.  Do not reuse this thread pool if task are long-running. 

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newCachedThreadPool();


Single thread pool executer:  Create single thread to execute all tasks. Its use when you want to execute single task.

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newSingleThreadPool();

Work stealing pool executer: Create a thread pool that maintain the enough thread to support the given parallelism level. Here  parallelism level means the maximum number of thread which will be used execute a given task, at single point of time, in multi-processor machine.

ThreadPoolExecuter executer=(ThreadPoolExecuter) Executer.newWorkStealingThreadPool();


Lets see example ...

MyTask.java

package com.samset.threads;
 
import java.util.concurrent.TimeUnit;
 
public class MyTask implements Runnable {
    private String name;
 
    public MyTask(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void run() {
        try {
            Long duration = (long) (Math.random() * 10);
            System.out.println("Executing : " + name);
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


Execute task with threadpoolexecuter

package com.samset.threads;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
 
public class ThreadPoolExample
{
    public static void main(String[] args)
    {
        ThreadPoolExecutor executor = (ThreadPoolExecutor)
Executors.newFixedThreadPool(2);
         
        for (int i = 1; i <= 5; i++)
        {
            MyTask task = new MyTask("Task " + i);
            System.out.println("Created : " + task.getName());
 
            executor.execute(task);
        }
        executor.shutdown();
    }
}


Output:

Created : Task 1
Created : Task 2
Created : Task 3
Created : Task 4
Created : Task 5
Executing : Task 1
Executing : Task 2
Executing : Task 3
Executing : Task 4
Executing : Task 5


ScheduledThreadExecutor: Fixed thread pools or cached thread pools are good when you have one unique task only once. When you need to execute a task repeatedly N times, either N fixed number of time or infinitely after fixed delay, you should be using ScheduledThreadPoolExecuter.
ScheduledThreadPoolExecuter provide 4 methods with different capability.
(1). Schedulefuture schedule(Runnable run,long deley,Timeunit unit)--> Create and executes a task that become enabled after the given delay.

(2). Schedulefuture schedule(Callable run,long deley,Timeunit unit)--> Create and executes a task schedulefuture that become enabled after the given delay.

(3). Schedulefuture scheduleAtFixedRate(Runnable run,long initialdelay,long deley,Timeunit unit)--> Create and executes periodic action that become enable first after the given initial delay, and subsequently with the given time period. If any execution of this task takes longer time than its period, then subsequent execution may start late, but will not concurrently execute.

(4). Schedulefuture scheduleAtFixedDelay(Runnable run,long initialdelay,long deley,Timeunit unit)--> Create and executes periodic action that become enable first after the given initial delay, and subsequently with the given time period. No matter how much time a long running task takes, there will be a fixed delay time gab between two execution.




package com.samset.threads;
 
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class ScheduledThreadPoolExecutorExample
{
    public static void main(String[] args)
    {
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2);
         
        Task task = new Task("Repeat Task");
        System.out.println("Created : " + task.getName());
         
        executor.scheduleWithFixedDelay(task, 2, 2, TimeUnit.SECONDS);
    }
}
 
class Task implements Runnable {
    private String name;
 
    public Task(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
 
    public void run() {
        System.out.println("Executing : " + name + ", Current Seconds : " + new Date().getSeconds());
    }
}

Output:

Created : Repeat Task
Executing : Repeat Task, Current Seconds : 36
Executing : Repeat Task, Current Seconds : 38
Executing : Repeat Task, Current Seconds : 41
Executing : Repeat Task, Current Seconds : 43
Executing : Repeat Task, Current Seconds : 45
Executing : Repeat Task, Current Seconds : 47



Thanks,
I hope now you better understand what is executer and how to work enjoy my friends.

1 comment:

  1. Slotz Casino Site – Lucky Club
    › site › slotz-casino › site › slotz-casino Lucky Club has been offering online casino games for over a decade. With over 1000 slot machines and the latest bonuses at our online casino, 카지노사이트luckclub

    ReplyDelete