开发者

Is there a simple way to tell what tasks a Java Executor is running at a given moment?

I'm sure I could hack something together which would enable me to figure this开发者_JAVA技巧 out, but I'm hoping there's an out-of-the-box solution I'm just missing. I read the docs but I didn't see anything.

My specific app is using a ThreadPoolExecutor backed by a DelayQueue, although I'm not sure that matters.

Thanks!


One simple approach: wrap your tasks with code which will call callback signalling start of new task, passing along all data you will want it to:

interface StartTaskWatcher {
    void taskStarted(Object data);
}

class StartTaskSignalingWrapper implements Runnable {
    private final Runnable task;
    private final String taskDescription;
    private final StartTaskWatcher startTaskWatcher;

    StartTaskSignalingWrapper(Runnable task, String taskDescription, StartTaskWatcher startTaskWatcher) {
        this.task = task;
        this.taskDescription = taskDescription;
        this.startTaskWatcher = startTaskWatcher;
    }

    public void run() {
        startTaskWatcher.taskStarted(taskDescription);
        task.run();
    }
}


I don't think there is a reliable way to do this. If you want counts there are methods available (getTaskCount()/getCompletedTaskCount()) which help. If you need the actual tasks then AFAIK you need manually to keep track of the tasks, by overriding beforeExecute() and afterExecute() is one way.


Do you actually need to know at runtime, or just for debugging?

If you're just debugging, consider taking a look at the JVisualVM application (installed in the 'bin' directory of the JDK). It lets you dynamically inspect all running threads, so it should be able to provide you with some insight.

(The JVisualVM can also perform CPU/Memory profiling, with execution & allocation hotspots, and shows garbage collection activity in realtime.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜