Reputation:
According to Java concurrency in practice if we want to add logging, timing, monitoring facility to ThreadPoolExecutor then we should extend it. Suppose if we extend it like below:
// code taken from java concurrency in practice
public class TimingThreadPool extends ThreadPoolExecutor
{
private final ThreadLocal<Long> startTime
= new ThreadLocal<Long>();
private final Logger log = Logger.getLogger("TimingThreadPool");
private final AtomicLong numTasks = new AtomicLong();
private final AtomicLong totalTime = new AtomicLong();
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
log.fine(String.format("Thread %s: start %s", t, r));
startTime.set(System.nanoTime());
}
protected void afterExecute(Runnable r, Throwable t) {
try {
long endTime = System.nanoTime();
long taskTime = endTime - startTime.get();
numTasks.incrementAndGet();
totalTime.addAndGet(taskTime);
log.fine(String.format("Thread %s: end %s, time=%dns",
t, r, taskTime));
} finally {
super.afterExecute(r, t);
}
}
protected void terminated() {
try {
log.info(String.format("Terminated: avg time=%dns",
totalTime.get() / numTasks.get()));
} finally {
super.terminated();
}
}
}
Here my doubt is how will you use this class, because if you create ExecutorService it always returns an instance of ThreadPoolExecutor. So how will u plug this class to show the loggings (need client code to use this).
Thanks in advance!!! Sorry if i made any mistake while mentioning the question.
Upvotes: 2
Views: 4482
Reputation: 136112
Your class is missing constuctors, it wont work without them
public class TimingThreadPool extends ThreadPoolExecutor {
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
// ...
}
Besides you could take a look at Executors
implementation and do something similar in your class
public static ExecutorService newFixedThreadPool(int nThreads) {
return new TimingThreadPool(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Upvotes: 4