Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for thread safe-ness?

I've written a class and many unit test, but I did not make it thread safe. Now, I want to make the class thread safe, but to prove it and use TDD, I want to write some failing unit tests before I start refactoring.

Any good way to do this?

My first thought is just create a couple threads and make them all use the class in an unsafe way. Do this enough times with enough threads and I'm bound to see it break.

like image 918
TheSean Avatar asked Nov 11 '09 15:11

TheSean


People also ask

How do you make a test thread-safe?

Tests for thread safety differ from typical single-threaded tests. To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens.

How can you tell if an object is thread-safe?

A method will be thread safe if it uses the synchronized keyword in its declaration. However, even if your setId and getId methods used synchronized keyword, your process of setting the id (if it has not been previously initialized) above is not. .. but even then there is an "it depends" aspect to the question.

What are unit test standards?

Unit tests are short, quick, and automated tests that make sure a specific part of your program works. They test specific functionality of a method or class that have a clear pass/fail condition. By writing unit tests, developers can make sure their code works, before passing it to QA for further testing.

When should I worry about thread safety?

Thread safety becomes a concern if there is at least a single entry point which can be accessed by multiple threads. If a piece of code is accessed by multiple threads and is calling other method/class/etc., then all this code tree becomes vulnerable.


1 Answers

There are two products that can help you there:

  • Microsoft Chess
  • Typemock Racer

Both check for deadlocks in your code (via unit test) and I think Chess checks for race conditions as well.

Using both tools is easy - you write a simple unit test and the run your code several times and check if deadlocks/race conditions is possible in your code.

Edit: Google has released a tool that checks for race condition in runtime (not during tests) that called thread-race-test.
it won't find all of the race conditions because it only analyse the current run and not all of the possible scenarios like the tool above but it might help you find the race condition once it happens.

Update: Typemock site no longer had a link to Racer, and it was not been updated in the last 4 years. I guess the project was closed.

like image 171
Dror Helper Avatar answered Oct 01 '22 01:10

Dror Helper