Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track task execution statistics using an ExecutorService?

I'm firing off tasks using an ExecutorService, dispatching tasks that need to be grouped by task-specific criteria:

Task[type=a]
Task[type=b]
Task[type=a]
...

Periodically I want to output the average length of time that each task took (grouped by type) along with statistical information such as mean/median and standard deviation.

This needs to be pretty fast, of course, and ideally should not cause the various threads to synchronize when they report statistics. What's a good architecture for doing this?

like image 286
Chris R Avatar asked May 28 '09 20:05

Chris R


People also ask

Can you give an example for ExecutorService?

Here is a code example: ExecutorService executorService = Executors. newSingleThreadExecutor(); Set<Callable<String>> callables = new HashSet<Callable<String>>(); callables. add(new Callable<String>() { public String call() throws Exception { return "Task 1"; } }); callables.

What is ExecutorService and how its works?

The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java. util. concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status.

Which are used to delegate tasks for execution to an ExecutorService?

We can assign tasks to the ExecutorService using several methods including execute(), which is inherited from the Executor interface, and also submit(), invokeAny() and invokeAll().


1 Answers

ThreadPoolExecutor provides beforeExecute and afterExecute methods that you can override. You could use those to record your statistics in a single (member variable of your ExecutorService) ConcurrentHashMap keyed on some unique identifier for your tasks, and storing the type, start time, and end time.

Calculate the statistics from the ConcurrentHashMap when you are ready to look at them.

like image 136
Adam Jaskiewicz Avatar answered Oct 14 '22 22:10

Adam Jaskiewicz