If you are using logging then thread names will be helpful. A thread factory helps with this:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class Main {
static Logger LOG = LoggerFactory.getLogger(Main.class);
static class MyTask implements Runnable {
public void run() {
LOG.info("A pool thread is doing this task");
}
}
public static void main(String[] args) {
ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
taskExecutor.execute(new MyTask());
taskExecutor.shutdown();
}
}
class MyThreadFactory implements ThreadFactory {
private int counter;
public Thread newThread(Runnable r) {
return new Thread(r, "My thread # " + counter++);
}
}
Output:
[ My thread # 0] Main INFO A pool thread is doing this task