Friday, October 28, 2022

Java - Always Name Your Thread Pools - Naming threads and thread-pools of ExecutorService - set name of thread

You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory).

The factory will be responsibe for creating threads, and will be able to name them.
ExecutorService is a JDK API that makes asynchronous task execution easier.

ExecutorService offers a pool of threads and an easy-to-use API for assigning tasks.

The ExecutorService gives the name of the threads in the thread pool.

This shot discusses how we can assign custom names to the threads of the thread pool of the ExecutorService.
BasicThreadFactory

An ExecutorService employs a ThreadFactory to create its threads to execute tasks.

In many circumstances, users do not need to worry about a ThreadFactory because the ExecutorService's default one will suffice.

A custom ThreadFactory must be constructed with particular needs, such as thread naming.
import java.util.TimerTask;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        // instant thread execution
        ExecutorService executorService = Executors.newFixedThreadPool(3, namedThreadFactory("test-thread"));
        for (int i=0; i < 5; i++) {
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        executorService.shutdown();

        // scheduled thread execution


        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(namedThreadFactory("scheduled-thread"));
        TimerTask repeatedTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName());
                }
                finally {
                    executor.shutdownNow();
                }
            }
        };
        executor.schedule(repeatedTask, 1L, TimeUnit.MINUTES);
    }

    static ThreadFactory namedThreadFactory(String name) {
        return new YourThreadFactory(name);
    }
}

class YourThreadFactory implements ThreadFactory {
    private String name = "[No Name]";

    YourThreadFactory(String name) {
        this.name = name;
    }

    public Thread newThread(Runnable r) {
        return new Thread(r, name);
    }
}

No comments:

Post a Comment