Reputation: 485
I am having a conceptual problem in understanding the working of fixedthreadpool of executor service.
Suppose I have a fixed pool thread of n threads and I am submitting several tasks to this service. Now if a worker is available, it executes the submitted task and other submitted tasks wait in the queue until a worker is free.
My question is, when do we consider a worker as a free worker thread ?
Do we consider a worker thread free as soon as it starts submitted task irrespective of task's completion or we consider a worker thread busy as long as submitted task is in progress.
Let's say we have a worker thread W1 in the pool and a Task Op1 is submitted to the executor.
W1 starts Op1 at time T1 and after some time Op1 finished its execution at time T3. Here T3 > T1
Now do we consider W1 as free as soon as it starts Op1 at time T1 or it is considered busy and will be free at time T3.
Thanks in advance !!
Upvotes: 1
Views: 1474
Reputation: 99
Well, it's very simple... let's get started.
runnable
interface, thus it has a run method that does not take any arguments and return void. This method acts as an entry point or the method that is called by the "thread that would be executing you task" in the thread pool.ArrayBlockingQueue
/LinkedBlockingQueue
, etc... The main point is: it is always a queue.
b. A group of threads that continuously poll this queue.The thread that executes your task looks like this some what
void run() { while (true) { //Get the task from the thread pool internal queue (1) //Call the run method of the task. //If the execution of the task throws a Runtime exception - catch it and display it. (2) } }
So, as u can see, the worker will only be free if there are no task in the queue. The worker would either be polling the queue for task (1) or executing the task (2).
Upvotes: 2
Reputation: 40256
A worker thread is free when it is takes
ing off the queue. Any given worker thread take's off the queue when it no longer is running the task. So it would look something like
private final BlockingQueue<Runnable> workQueue;
class WorkerThread {
public void run(){
while(true){
Runnable r = workQueue.take(); // worker thread is 'free'
r.run(); // worker thread is busy
}
}
}
So to answer your question, a particular worker thread is free when it is not executing a task submitted to the service.
Upvotes: 2