Any satisfactory approaches to unit testing thread safety in Java?

后端 未结 5 1580
孤街浪徒
孤街浪徒 2021-01-31 08:01

I am looking at improving a package that I believe not to be threadsafe when its input is shared between multiple worker threads. According to TDD principles, I should write so

5条回答
  •  不思量自难忘°
    2021-01-31 08:33

    Java Concurrency in Practice has some great information about how to write tests for concurrency issues. However they are not true unit tests. It is nearly impossible to write a true unit test for a concurrency issue.

    Basically it boils down to this. Create a bunch of test threads and start them. Each thread should

    • wait for a count down latch
    • repeatedly call some method that modifies the mutable state in question
    • count down on a second latch and exit

    The junit thread creates all the threads and starts them, then counts down on the first latch once to let them all go, then waits for the second latch, then makes some assertions about the mutable state.

    Even more so than other types of bugs, it's easier to write a failing unit test for a concurrency bug after you have found the bug.

提交回复
热议问题