views:

97

answers:

4

All,

Recently I developed a code that supposedly is a thread-safe class. Now the reason I have said 'supposedly' is because even after using the sync'ed blocks, immutable data structures and concurrent classes, I was not able to test the code for some cases because of the thread scheduling environment of JVM. i.e. I only had test cases on paper but could not replicate the same test environment. Is there any specific guidelines or something the experienced members over here who can share about how to test a multi-threaded environment.

+9  A: 

First thing is, you can't ensure only with testing that your class is fully thread-safe. Whatever tests you run on it, you still need to have your code reviewed by as many experienced eyes as you can get, to detect subtle concurrency issues.

That said, you can devise specific test scenarios to try to cover all possible inter-thread timing scenarios, as you did. For ideas on this (and for designing thread-safe classes in general), it is recommended to read Java Concurrency in Practice.

Moreover, you can run stress tests, executing many threads simultaneously over an extended period of time. The number of threads should be way over the reasonable limit to make sure that thread contention happens often - this raises the chances of potential concurrency bugs to manifest over time.

Péter Török
Experienced eyes and stress tests - total +1 :)
aperkins
Excellent answer.
Willi
+1 For the book
Jayan
Thanks Peter for your suggestion
darkie15
+1  A: 

Also, another thing I would recomend is for you to use code coverage measuring tools and set a high standar as your goal. For example, set a high goal for modified condition/decision coverage.

EKI
got it .. thanks you
darkie15
This certainly is useful in general, but it may not necessarily help much when testing concurrent code. It is good for ensuring that most or all possible execution paths are traversed _within a single thread_. But it doesn't have any effect on inter-thread timing, which is the root of concurrency issues.
Péter Török
Hmmm... the point I was trying to make is that the elements that regulate the inter-thread timing shall be executed in as much completeness as possible. If you could ensure that a stress-test scenario has exercised at some point all the possible decisions in all its variants, you could say that the stress-test has been appropriately designed and therefore your application has been properly verified.Also, I have found this link that might be useful... (http://www.springerlink.com/content/b2jk158074366499/)
EKI
+1  A: 

We use GroboUtils to create multi threaded tests.

Jayan
thanks a lot !!
darkie15
A: 

If you have code that you plan to test in order to make it reliable, then make it single threaded.

Threading should be reserved for code that either doesn't particularly need to work, or is simple enough to be statically analysed and proven correct without testing.

soru