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?
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.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With