Foojay Today

Daemon Thread Java Code Quiz

September 08, 2021

When we are working with Threads, it’s important to know when to use a daemon or a non-daemon Thread.

Do you know if the main Thread is a daemon or not? And do you know what a daemon Thread is?

That’s what you will find out by trying out the following Java Challenge!

It's time to improve your Java skills with this Daemon Thread Challenge...

Daemon Thread Challenge

What will happen when running the following main method?

public class DaemonThreadChallenge implements Runnable {

        public static void main(String... doYourBest) {
            Thread thread = new Thread(new DaemonThreadChallenge());
            thread.setDaemon(true);
            thread.start();
        }

        @Override
        public void run() {
            for (;;) {
                System.out.println("For ever");
            }
        }
}

A) It will print "Forever" for an indeterminate time and the program will finish normally.
B) It will throw StackOverflowError because of the infinite looping.
C) It will print "Forever" infinitely.

Explanation:

The amount of time that "Forever" will be printed is indeterminate because it will depend on the time from the main thread execution.

There are two types of threads:

  • Non-daemon: the main method is executed with a non-daemon thread behind the scenes and this thread will be executed until the end.
  • Daemon: it will die if all non-daemon threads have finished. So in this quiz, if the main method is finished, the daemon thread we created will be finished as well because all daemon threads depend on a non-daemon thread to continue its execution.

Therefore, the final answer will be... what do you think?

That's it challenger, keep pushing your limits to be a better software developer!

Topics:

Author(s)

  • Rafael del Nero

    Java Champion, a passionate and creative developer who possesses strong technical knowledge and delivers solid systems focused on Spring and Java EE specifications for cloud applications. More than 10 years' ... Learn more

Comments (0)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard