Turning an ExecutorService to daemon in Java

后端 未结 8 2237
无人共我
无人共我 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:18

    Probably simplest and preferred solution is in Marco13's answer so don't get fooled by vote difference (mine answer is few years older) or acceptance mark (it just means that mine solution was appropriate for OP circumstances not that it is best).


    You can use ThreadFactory to set threads inside Executor to daemons. This will affect executor service in a way that it will also become daemon thread so it (and threads handled by it) will stop if there will be no other non-daemon thread. Here is simple example:

    ExecutorService exec = Executors.newFixedThreadPool(4,
            new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = Executors.defaultThreadFactory().newThread(r);
                    t.setDaemon(true);
                    return t;
                }
            });
    
    exec.execute(YourTaskNowWillBeDaemon);
    

    But if you want to get executor which will let its task finish, and at the same time will automatically call its shutdown() method when application is complete, you may want to wrap your executor with Guava's MoreExecutors.getExitingExecutorService.

    ExecutorService exec = MoreExecutors.getExitingExecutorService(
            (ThreadPoolExecutor) Executors.newFixedThreadPool(4), 
            100_000, TimeUnit.DAYS//period after which executor will be automatically closed
                                 //I assume that 100_000 days is enough to simulate infinity
    );
    //exec.execute(YourTask);
    exec.execute(() -> {
        for (int i = 0; i < 3; i++) {
            System.out.println("daemon");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    

提交回复
热议问题