Turning an ExecutorService to daemon in Java

后端 未结 8 2180
无人共我
无人共我 2020-11-27 02:39

I am using an ExecutoreService in Java 1.6, started simply by

ExecutorService pool = Executors.newFixedThreadPool(THREADS). 

When my main

相关标签:
8条回答
  • 2020-11-27 03:23

    You can use Guava's ThreadFactoryBuilder. I didn't want to add the dependency and I wanted the functionality from Executors.DefaultThreadFactory, so I used composition:

    class DaemonThreadFactory implements ThreadFactory {
        final ThreadFactory delegate;
    
        DaemonThreadFactory() {
            this(Executors.defaultThreadFactory());
        }
    
        DaemonThreadFactory(ThreadFactory delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = delegate.newThread(r);
            thread.setDaemon(true);
            return thread;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:24

    If you only want to use it in one place, then you can inline the java.util.concurrent.ThreadFactory implementation, e.g. for a pool with 4 threads you would write (example shown as a lambda assuming Java 1.8 or newer):

    ExecutorService pool = Executors.newFixedThreadPool(4,
            (Runnable r) -> {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
    );
    

    But I usually want all of my Thread factories to produce daemon threads, so I add a utility class as follows:

    import java.util.concurrent.ThreadFactory;
    
    public class DaemonThreadFactory implements ThreadFactory {
    
        public final static ThreadFactory instance = 
                        new DaemonThreadFactory();
    
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    }
    

    That allows me to easily pass DaemonThreadFactory.instance to the ExecutorService, e.g.

    ExecutorService pool = Executors.newFixedThreadPool(
        4, DaemonThreadFactory.instance
    );
    

    or use it to easily start a daemon Thread from a Runnable, e.g.

    DaemonThreadFactory.instance.newThread(
        () -> { doSomething(); }
    ).start();
    
    0 讨论(0)
提交回复
热议问题