在Java中单元测试线程安全的任何令人满意的方法? [英] Any satisfactory approaches to unit testing thread safety in Java?

查看:140
本文介绍了在Java中单元测试线程安全的任何令人满意的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在多个工作线程之间共享输入时改进我认为不是线程安全的包。根据TDD原则,我应该编写一些在第一个实例中失败的测试,这些测试在评估问题时肯定会有用。

I am looking at improving a package that I believe not to be threadsafe when its input is shared between multiple worker threads. According to TDD principles, I should write some tests that fail in the first instance, and these would certainly be useful in assessing the problem.

我意识到这不是一个实现简单的事情,并且天真地,多线程测试将是不确定的,因为操作系统将确定调度以及各种操作交错的确切顺序。我过去曾查看并使用过 MultithreadedTC 很有用。但是,在这种情况下,我事先知道现有实现的确切位置,从而能够完成一系列覆盖它的测试。

I realise that this is not a simple thing to acheive, and that naively, multi-threaded tests will be nondeterministic as the operating system will determine scheduling and the exact order that various operations are interleaved. I have looked at and used MultithreadedTC in the past, and this was useful. However, in that case I knew in advance exactly where the existing implementation fell down, and thus was able to cook up a nice set of tests that covered it.

但是,如果你还没有确切知道问题是什么,那么是否有一种很好的方法来编写一个很有可能抛出任何潜在问题的测试?是否有其他人发现有用的图书馆?我是否正确地认为,从纯粹主义的角度来看,多线程测试用例应该与通常的单线程测试一样,只能与多个工作线程一起运行?

However, if you're not at the point where you know exactly what the problem is, is there a good way of going about writing a test that stands a good chance of throwing up any potential problems? Are there any libraries that others have found helpful? Would I be right in thinking that from a purist point of view, a multi-threaded test case should just be the same calls and assertions as the usual single-threaded test, only run with multiple worker threads as appropriate?

欢迎提供有关工具/最佳实践/理念的任何优惠。

Any offers on tools/best practices/philosophy in general would be welcome.

推荐答案

通过测试并发性问题,忘记获得好的结果。尝试减少同步并使问题变小。然后使用尽可能高的库支持来进行同步。只有你真的有尝试自己处理并发。当你知道每个工作人员的工作正确并且你所有的想法告诉你你有并发问题时,就会产生一些有趣的负载。 Unittest框架及其扩展可以完成这项工作,但知道你不再测试任何单元了。 (记住,你已经覆盖了那部分)

Forget getting good results by testing for concurrency problems. Attempt to reduce synchronization and make the problem smaller. Then use as high as possible library support to do synchronization. And only if you really have then try to handle the concurrency yourself. When you know each worker does its work correct and all your thinking tell you that you have the concurrency problem licked then generate some interesting load. Unittest frameworks and their extensions can do that job, but know that you are not testing any units anymore. (Remember, you already had that part covered)

如果您的并发模型变得复杂,请查看适用于此类的工具,例如 SPIN

If your concurrency model gets complicated check out tools suited for that like SPIN.

这篇关于在Java中单元测试线程安全的任何令人满意的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆