3

I've got some code that forgets to set the daemon flag on a thread. Thus, main methods don't ever complete. I'll track it down eventually, but I wonder: is there any way to reflectively notice the existence of non-daemon threads so that a JUnit (or testng, or whatever) test could complain in this case? Note that these test frameworks orchestrate System.exit so that the excess threads don't manifest as hangs.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • How would you want this reported? Just that such a thread exists, or some sort of pin-point on where the thread was created? – Brick Oct 06 '16 at 17:22
  • Just its existence. ThreadMXBean does not show the daemon flag, if it did, that would be enough. – bmargulies Oct 06 '16 at 17:32

1 Answers1

2

You can get a list of all running threads (Get a List of all Threads currently running in Java):

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

Then you can iterate through the list in some test that you write calling Thread.isDaemon(). You'll probably need to throw out some threads that correspond to the JVM or the JUnit framework, but that's probably doable by checking other aspects of the threads, like their name.

Community
  • 1
  • 1
Brick
  • 3,998
  • 8
  • 27
  • 47