简体   繁体   English

我可以在Junit测试中检测到泄漏的线程吗?

[英]Can I detect a leaked thread in a Junit test?

I've got some code that forgets to set the daemon flag on a thread. 我有一些忘记在线程上设置守护进程标志的代码。 Thus, main methods don't ever complete. 因此, main方法永远不会完成。 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? 我最终会跟踪它,但我想知道:有没有办法反思地注意到非守护程序线程的存在,以便在这种情况下JUnit(或testng,或其他)测试可能会抱怨? Note that these test frameworks orchestrate System.exit so that the excess threads don't manifest as hangs. 请注意,这些测试框架编排System.exit以便多余的线程不会显示为挂起。

You can get a list of all running threads ( Get a List of all Threads currently running in Java ): 您可以获取所有正在运行的线程的列表获取当前在Java中运行的所有线程的列表 ):

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

Then you can iterate through the list in some test that you write calling Thread.isDaemon() . 然后,您可以在编写调用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. 您可能需要抛弃一些与JVM或JUnit框架相对应的线程,但这可能通过检查线程的其他方面(如名称)来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM