Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidelines for testing multithreaded code or ensuring that code is thread-safe

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?

like image 520
Vivin Paliath Avatar asked Dec 14 '10 21:12

Vivin Paliath


1 Answers

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.

like image 88
Jed Wesley-Smith Avatar answered Oct 19 '22 22:10

Jed Wesley-Smith