测试多线程代码或确保代码是线程安全的准则 [英] Guidelines for testing multithreaded code or ensuring that code is thread-safe

查看:167
本文介绍了测试多线程代码或确保代码是线程安全的准则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关测试多线程代码的任何指南(不是在问题上抛出一堆线程,而是跨越你的手指)。



我基本上看为测试数据损坏,死锁和其他并发问题的好方法。基本上我想要能够通过测试证明代码是线程安全的。



Java中是否有任何框架,您可以轻松地为多线程场景编写测试?

解决方案

我写了很多多线程代码,从来没有发现任何东西,可以轻松地测试并发正确性问题,我没有预测。大多数时候,我必须考虑它可能会破裂的情况,然后我将如何证明其正确性的极端版本​​(通常使用CountDownLatches或类似的方式,我折腾它的方式,我认为它可能会破裂。 p>

绝对使用FindBugs和类似的静态分析工具来帮助发现潜在的问题,并确保你的并发问题尽可能简单。共享的可变内存问题很难,但实际上很容易重新定义问题所以你不共享可变状态,只有不变的状态,这使得生活更简单哦,阅读JCiP,然后再读一遍,并让你的代码审查。


Are there any guidelines for testing multi-threaded code (other than throwing a bunch of threads at the problem and crossing your fingers).

I'm basically looking for good ways to test for data corruption, deadlocks, and other concurrency issues. Essentially I want to be able to prove that the code is thread-safe via a test.

Are there any frameworks in Java that let you easily write tests for a multithreaded scenario?

解决方案

I have written a lot of multi-threaded code and have never found anything much that can easily test for concurrency correctness issues that I haven't predicted. Most of the time I have to think about the scenario in which it may break and then how I might prove its correctness in an extreme version of this (often using CountDownLatches or similar to bend it in the ways I think it may break.

Definitely use FindBugs and similar static analysis tools to help find potential problems, and definitely keep your concurrency problems as simple as possible. Shared mutable memory problems are hard but it is actually quite easy to redefine the problem so you don't share mutable state, only immutable state. That makes life much simpler. Oh, and read JCiP – then read it again. And get your code reviewed.

这篇关于测试多线程代码或确保代码是线程安全的准则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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