ealeon
ealeon

Reputation: 12462

Java thread equivalent of Python thread daemon mode

In python I can set a thread to be a daemon, meaning if parent dies, the child thread automatically dies along with it.

Is there an equivalent in Java?

Currently I am starting a thread like this in Java, but the underlying child thread does not die and hang even if main thread exits

         executor = Executors.newSingleThreadExecutor();
         executor.submit(() -> {
             while (true) {
                 //Stopwatch stopwatch = Stopwatch.createStarted();

                 String threadName = Thread.currentThread().getName();
                 System.out.println("Hello " + threadName);
                 try {
                     Thread.sleep(1*1000);
                 } catch (InterruptedException e) {
                     break;
                 }   

             }       
         });

Upvotes: 0

Views: 230

Answers (1)

Maciej Dobrowolski
Maciej Dobrowolski

Reputation: 12130

When you're interacting with bare Thread you can use:

Thread thread = new Thread(new MyJob());
thread.setDaemon(true);

thread.start();

In your example, there's ExecutorService that needs to be provided with ThreadFactory which should do the similar job - like this:

Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);

        return thread;
    }
});

I would also recommend using Guavas ThreadFactoryBuilder:

Executors.newSingleThreadExecutor(
        new ThreadFactoryBuilder()
                .setDaemon(true)
                .build()
); 

It eases setting the most common thread properties and allows for chaining multiple thread factories

update

As Slaw and Boris the Spider rightfully noticed - you have mentioned the behavior that would cause killing child-thread when parent-thread dies. There's nothing like that either in Python or Java. Daemon threads will be killed when all other non-daemon threads exited.

Upvotes: 1

Related Questions