Question

First of: I'm not that familiar with Threading in general, though I know some of the basics (atleast, I think).

Now, after using the ExecutorService to create a FixedThreadPool, is it possible to keep track of a certain 'position' in this threadpool?

Example:

Create a new threadpool:

ExecutorService es = Executors.newFixedThreadPool(5);

Start some threads:

for (int i = 0; i < 10; i++) {
    es.execute(new Runnable()); //Implementation does not matter
}

Now, what will happen is that 5 threads will get executed, while the other 5 will be queued. Let's say the 3rd started thread is done, so the ExecutorService starts a task thread to top up the maximum of 5 threads again.

Is there a possible way of getting the new thread on that previously third position? Or in what order do threads get executed when the service has room for more threads.

I'd like to know this, because I want to implement some kind of 'thread table', in which you can see which Threads are running and which aren't (something similar to a task manager, but way less technical/advanced, just for a simple webcrawler).

Thanks in advance and please, don't blame me if this is a very 'noobish' or stupid question, as I have little experience with Threading and would just like to know whether this is possible.

Was it helpful?

Solution

so the ExecutorService starts a new thread to top up the maximum of 5 threads again.

No, it keep the same 5 threads running until you shutdown the pool, even if those threads have nothing to do.

Is there a possible way of getting the new thread on that previously third position?

With a ThreadFactory you can create each thread as needed, e.g. to change the thread name, or make it a daemon. As I mentioned there isn't one created, so you won't be told.

Or in what order do threads get executed when the service has room for more threads.

The pool creates 5 threads before you have any jobs, and they keep running. There is no free slots as such.

I'd like to know this, because I want to implement some kind of 'thread table', in which you can see which Threads are running and which aren't (something similar to a task manager, but way less technical/advanced, just for a simple webcrawler).

I suggest using VisualVM. It shows you all the thread which are running/blocking/waiting etc. Giving your threads meaningful names is useful. ;)

enter image description here

[how to detect when it] "execute a new task".

You can sub-class the ThreadPoolExecutor. It has two methods

 protected void beforeExecute(Thread t, Runnable r)

which will let you know when a thread is about to start a Runnable and

 protected void afterExecute(Runnable r, Throwable t)

which is called when a task has finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top