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

五迷三道 提交于 2019-11-29 03:59:28

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.

So, I've got a solution that manages both to set the name and clean up after the name. Thank you to both Peter Lawrey and John Vint for their suggestions which led me here. Since neither suggestion fully handled my problem I figured I'd post this sample code as a separate answer. I apologize if that's poor etiquette--if so, let me know and I'll adjust.

In the below code I decided to keep the name of the original ThreadPoolExecutor thread and append the Runnable name, then in the finally block remove the Runnable name to clean up, but that can be easily altered.

As John Vint suggests, I'd prefer to override the beforeExecution method and then override the afterExecution method to clean up, but the afterExecution does not have a handle to the thread.

public class RunnableNameThreadPoolExecutor extends ThreadPoolExecutor {

    /* Constructors... */

    @Override
    public void execute(Runnable command) {
        super.execute(new ManageNameRunnable(command));
    }

    private class ManageNameRunnable implements Runnable {
        private final Runnable command;
        ManageNameRunnable( Runnable command ) {
            this.command = command;
        }

        public void run() {
            String originalName = Thread.currentThread().getName();
            try {
                String runnableName = getRunnableName(command);
                Thread.currentThread().setName(originalName+ ": " + runnableName);
                command.run();
            } finally {
                Thread.currentThread().setName(originalName);
            }
        }
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!