Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we save a thread for next task after its execution in java (Implementation of Thread pooling )

I need to ask about how thread pooling is implemented for having constant number of thread executing each time when there is task submission happened . (In Executor to avoid each time thread creation and deletion overhead)

executor.submit(Runnable)

Lets say we create some threads in the start and when task come we assign task to them(Thread) using any Queue impl . But after completing it s task how could a thread return to its pool again when as per the lifecycle of thread says that

"After execution of its run method it goes into TERMINATED state and can't be used again"

I am not understood how thread pool works for having constant number of threads for execution of any task to its queue .

It would be great if anyone could provide me an example of thread reuse after its completion of task .

!!Thanks in advance .!!

like image 321
Virendra Avatar asked Oct 07 '22 10:10

Virendra


1 Answers

"After execution of its run method it goes into TERMINATED state and can't be used again"

It doesn't finish its run() Instead it has a loop which runs the run() of the tasks you provide it.


Simplifying the thread pool pattern dramatically you have code which looks like this.

final BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>();

public void submit(Runnable runs) {
    tasks.add(runs);
}

volatile boolean running = true;

// running in each thread in the pool
class RunsRunnable implement Runnable {
    public void run() {
        while(running) {
           Runnable runs = tasks.take();
           try {
              runs.run();
           } catch(Throwable t) {
              // handles t
           }
        }
    }
 }

In this example, you can see that while the run() of each task completes, the run() of the thread itself does not until the pool is shutdown.

like image 151
Peter Lawrey Avatar answered Oct 11 '22 02:10

Peter Lawrey