Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nkcoder
Created February 5, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkcoder/25cecec15bf4f3c6b19cf7afaa4151af to your computer and use it in GitHub Desktop.
Save nkcoder/25cecec15bf4f3c6b19cf7afaa4151af to your computer and use it in GitHub Desktop.
extending ThreadPoolExecutor, add timing log
package org.nkcoder.module.javatest.concurrent;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/**
* created by daniel at 2/5/17 22:54
*/
public class TimingThreadPool extends ThreadPoolExecutor {
private final Logger logger = Logger.getLogger("TimingThreadPool");
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
private final AtomicLong numTasks = new AtomicLong();
private final AtomicLong totalTime = new AtomicLong();
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
startTime.set(System.nanoTime());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
try {
long endTime = System.nanoTime();
long taskTime = endTime - startTime.get();
totalTime.addAndGet(taskTime);
numTasks.incrementAndGet();
} finally {
super.afterExecute(r, t);
}
}
@Override
protected void terminated() {
try {
logger.info(String.format("totalTime: %dns, numTasks: %d", totalTime.get(), numTasks.get()));
} finally {
super.terminated();
}
}
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
public static void main(String[] args) {
TimingThreadPool threadPool = new TimingThreadPool(3, 3, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
for (int i = 0; i < 5; i++) {
threadPool.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println("all tasks have submitted.");
threadPool.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment