Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Suicide on Shutdown? stopping java.util.Timer instance

I have a java.util.Timer running at a fixed interval. I have added a Runtime#addShutdownHook and it shuts down when the VM ends normally or abnormally. However, it keeps the VM alive when a main terminates, unless I insist by doing a System.exit in the main. Is there any way for me to check if I'm the last Thread standing, or some other way to avoid altering a main that would exit normally on finish?

Note: I know a lot of people believe that java.util.Timer is deprecated (it's not), but unless your alternative helps me solve this problem...

like image 486
Dan Rosenstark Avatar asked Feb 27 '23 01:02

Dan Rosenstark


1 Answers

Create the timer using one of the constructor overloads which allows you to specify whether to use a daemon thread: pass true in as the argument, so that it will run on a daemon thread, which won't prevent the VM from shutting down.

like image 62
Jon Skeet Avatar answered Apr 06 '23 23:04

Jon Skeet