Friday, October 21, 2011

How to Set Name in the Threads Created by ExecutorService

If we create a java.util.concurrent.ExecutorService without any argument, it will use DefaultThreadFactory, which has a pre-defined thread name, e.g. pool-n-thread-. To be able to set a different name for threads created by the ExecutorService, we need to create our own ThreadFactory like the example below.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThreadFactory implements ThreadFactory {

    private final String name;
    private final AtomicInteger integer = new AtomicInteger(1);
    
    public MyThreadFactory(String name) {
        this.name = name;
    }
    
    /** 
     * {@inheritDoc}
     */
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, name + integer.getAndIncrement());
    }
    
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(5, 
            new MyThreadFactory("Test"));
        try {
            for (int i = 1; i <= 5; i++) {
                es.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println(String.format("[%s] Sleeping for 3 secs",
                                Thread.currentThread().getName()));
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        finally {
            es.shutdown();
            try {
                es.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

No comments:

Post a Comment