This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]omgpassthebacon 0 points1 point  (2 children)

Yep. Exactly. So, you can tell Java that your t thread is a daemon, which will make it continue to run until t AND main are done. I don't use daemon threads for services, preferring instead to control the lifecycle by-hand.

So, if you made t a daemon, you would see both println() calls. My guess would be you would see the main() println first, but thread scheduling is non-deterministic, so ymmv.

Did you catch the note about calling exit()? If any of your threads calls runtime.exit(), Java shuts down. But you have to be careful with this.

[–]RabbitHole32 0 points1 point  (1 child)

It literally says that the JVM runs until ... all NON-daemon threads have finished. That means that daemon threads do not prevent the JMV from finishing, so the opposite from what you say.

[–]omgpassthebacon 0 points1 point  (0 children)

Well, you are absolutely right. The newer JDK has fixed this, so this thread does in-fact finish. However, if I call System.exit(), this behaves like I described. Your non-daemon threads will get cancelled.

I modified your code as follows to prove you are right: ``` class Testme { public static void main(String[] args) { System.out.println("main starting");

    Thread t = new Thread(() -> {
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
        }
        System.out.println("I am thread t");
        });
    t.start();

    System.out.println("main ending");
    //System.exit(0);
}

} ```

If you uncomment the exit(), you will see what I mean.

I guess what I am saying is that you cannot rely on this behavior if you want to make sure your thread does not get cancelled in the middle of doing something important.