Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With ThreadPoolExecutor, how to get the name of the thread running in the thread pool?

I'm using a ThreadPoolExecutor in Java to manage a lot of running threads. I've created my own simple ThreadFactory so I can give the threads better names.

The issue is that the name gets set in the Thread when the thread pool is first created and is not tied to the task that the thread pool is actually running. I understand this... my Runnables and Callables--though they have names--are actually one level of abstraction down from the ThreadPoolExecutor's running threads.

There have been some other questions on StackOverflow about creating names for ThreadPoolExecutor thread pools. (See How to give name to a callable Thread? and How to name the threads of a thread pool in Java.)

What I want to know is: does anyone have a good solution for keeping the name of the thread pool thread in sync with the Runnable that it is actually running?

i.e. If I call Thread.getCurrentThread().getName() I'd like it not to return the name of the top-level thread pool, but rather the name of the Callable/Runnable that the thread is currently running.

Since this is mainly for debugging and logging purposes, I'm trying to avoid a solution that involves me putting new code into every Runnable that might be submitted to the ThreadPoolExecutor--I'd rather just put some code into the ThreadFactory or wrap the ThreadPoolExecutor itself so that the change is done in one place. If such a solution doesn't exist I probably won't bother since it's not mission critical.

begin edit To clarify, I know I can put a Thread.currentThread().setName( "my runnable name" ); as the first line of every Runnable's run method, but I'm trying to avoid doing that. I'm being a perfectionist here, and I realize it, so I won't be offended if people want to comment on this question and tell me so. end edit

My other question, I suppose, is whether people think it's a bad idea to do such a thing. Should I be wary of updating the thread pool name like this?

Thanks for any suggestions!

like image 624
Jeff Goldberg Avatar asked Dec 15 '11 16:12

Jeff Goldberg


People also ask

How do you get results from ThreadPoolExecutor?

You can get results from the ThreadPoolExecutor in the order that tasks are completed by calling the as_completed() module function. The function takes a collection of Future objects and will return the same Future objects in the order that their associated tasks are completed.

Does Python ThreadPoolExecutor reuse threads?

Heterogeneous tasks, not homogeneous tasks. Reuse threads, not single use. Manage multiple tasks, not single tasks.

How do I find the thread ID in Python?

In Python 3.3+, you can use threading. get_ident() function to obtain the thread ID of a thread. threading. get_ident() returns the thread ID of the current thread.

How do I check if a Python thread is running?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.


2 Answers

My suggestion would be to try

pool.execute(new Runnable() {
    public void run() {
         Thread.getCurrentThread().setName("My descriptive Runnable");
         // do my descriptive Runnable
    }
});                 

You can also reset the name when you have finished if you like.

like image 186
Peter Lawrey Avatar answered Sep 20 '22 00:09

Peter Lawrey


Create a ThreadPoolExecutor that overrides the beforeExecute method.

private final ThreadPoolExecutor executor = new ThreadPoolExecutor (new ThreadPoolExecutor(10, 10,  0L, TimeUnit.MILLISECONDS,  new LinkedBlockingQueue<Runnable>()){   
    protected void beforeExecute(Thread t, Runnable r) { 
         t.setName(deriveRunnableName(r));
    }

    protected void afterExecute(Runnable r, Throwable t) { 
         Thread.currentThread().setName("");
    } 

    protected <V> RunnableFuture<V> newTaskFor(final Runnable runnable, V v) {
         return new FutureTask<V>(runnable, v) {
             public String toString() {
                return runnable.toString();
             }
         };
     };
}

Not sure how exactly derveRunnableName() would work, maybe toString()?

Edit: The Thread.currentThread() is in fact the thread being set in beforeExecute which calls the afterExecute. You can reference Thread.currentThread() and then set the name in the afterExecute. This is noted in the javadocs

/**
 * Method invoked upon completion of execution of the given Runnable.
 * This method is invoked by the thread that executed the task. If
 * non-null, the Throwable is the uncaught <tt>RuntimeException</tt>
 * or <tt>Error</tt> that caused execution to terminate abruptly.
 *
 * <p><b>Note:</b> When actions are enclosed in tasks (such as
 * {@link FutureTask}) either explicitly or via methods such as
 * <tt>submit</tt>, these task objects catch and maintain
 * computational exceptions, and so they do not cause abrupt
 * termination, and the internal exceptions are <em>not</em>
 * passed to this method.
 *
 * <p>This implementation does nothing, but may be customized in
 * subclasses. Note: To properly nest multiple overridings, subclasses
 * should generally invoke <tt>super.afterExecute</tt> at the
 * beginning of this method.
 *
 * @param r the runnable that has completed.
 * @param t the exception that caused termination, or null if
 * execution completed normally.
 */
protected void afterExecute(Runnable r, Throwable t) { }

Edit The TPE will wrap the Runnable within a FutureTask, so to support the toString method you could override newTaskFor and create your own wrapped FutureTask.

like image 38
John Vint Avatar answered Sep 19 '22 00:09

John Vint