5 Replies Latest reply on Feb 16, 2017 1:11 PM by Laird Nelson

    Behavior of non-daemon threads in CDI 2.0?

    Laird Nelson Apprentice

      Maybe I'm missing something obvious.  :-)

       

      It's my understanding that a JVM will exit when (a) Runtime.exit() is called in some way (let's forget about this case) or (b) there are no non-daemon threads left running.

       

      I'm seeing something that looks odd to me in a CDI 2.0 SE situation.

       

      I'm using the container startup recipe found here: SeContainerInitializer (CDI APIs 2.0-PFD API) (so the try-with-resources loop).

       

      Within the try-with-resources loop, on the main thread, I am creating a new Grizzly HttpServer.  Then I'm calling start() on it, which starts the server on a daemon thread.  Obviously if I do nothing else, the non-blocking start() call returns, the container auto-closes, and the VM exits.  This all makes sense to me since the only other thread created is the one created by the HttpServer.start() call, and that is a daemon (you can verify this by looking at the Grizzly HttpServer source code).

       

      I tried (just for experimenting) to create a new non-daemon thread and have it call HttpServer.start(), followed immediately by Thread.currentThread().join().  My thought was: OK, this new thread, being a non-daemon, would prevent the VM from exiting, since it would join() on itself and thus never die.

       

      If that's all I did, then I would expect the main loop to carry on, and so I'd expect the container to close.  But I would expect that my non-daemon thread would still be alive, and so consequently I'd expect that the VM would just block.

       

      But instead, I see the container close and the VM exit .  I placed a println after my join() call to see if somehow the join() call was being exited prematurely.  It's not.  I catch Exception and log it--but I'm not seeing any InterruptedExceptions.  Basically, what I'm seeing is that my non-daemon thread correctly enters the join() call, where it proceeds to wait "forever", just as I'd expect...and then the VM exits anyway (and I don't really know how my thread is dying without being interrupted).  I can't come up with an explanation for how this could be happening, unless Weld is somehow aggressively killing child threads in some fashion when it closes the container.

       

      Does Weld aggressively kill threads (surely not)?  What piece of the puzzle am I missing here?