6

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?

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • 4
    What about doing code reviews? Many common mistakes are relatively easy to spot once you assume they are there. – Erich Kitzmueller Dec 14 '10 at 21:34
  • This is about testing tools, not guidelines, but maybe it will help you: http://stackoverflow.com/questions/3256064/how-to-write-multi-threaded-unit-tests – Todd Dec 14 '10 at 21:35
  • Might want to look at the following related question: http://stackoverflow.com/questions/1634378/is-there-a-tool-for-java-similar-to-microsofts-chess – Guy Dec 14 '10 at 21:35
  • One way is load...increase the load on the code in question to see what surfaces and make use of jconsole and the detect deadlock button if you suspect something suspicious...load for the most part always exposed numerous issues with regards to threading for obvious reasons. – Aaron McIver Dec 14 '10 at 21:42
  • 1
    @ammoQ Yes, I already do code-reviews and those definitely help. However, things can slip by a code review. I think having a test in addition to a code review would be even more helpful. – Vivin Paliath Dec 14 '10 at 21:51
  • This [thread](http://stackoverflow.com/questions/4418373/designing-a-test-class-for-a-custom-barrier/4427499#4427499) has some general comments. – Toby Dec 15 '10 at 08:53
  • While not an exact duplicate, the answers here should help: http://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code – Warren Dew Apr 15 '17 at 23:13

2 Answers2

3

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.

Jed Wesley-Smith
  • 4,686
  • 18
  • 20
0

GroboUtils, http://groboutils.sourceforge.net/testing-junit/using_mtt.html, provides some JUnit utilities for testing Threads.

Paul Croarkin
  • 14,496
  • 14
  • 79
  • 118