Using TDD to drive out thread-safe code

前端 未结 6 1644
清酒与你
清酒与你 2020-12-13 22:26

What\'s a good way to leverage TDD to drive out thread-safe code? For example, say I have a factory method that utilizes lazy initialization to create only one instance of

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 23:17

    You could inject a "provider" (a really simple factory) that is responsible for just this line:

     textLineEncoder = new TextLineEncoder();
    

    Then your test would inject a really slow implementation of the provider. That way the two threads in the test could more easily collide. You could go as far as have the first thread wait on a Semaphore that would be released by the second thread. Then success of the test would ensure that the waiting thread times out. By giving the first thread a head-start you can make sure that it's waiting before the second one releases.

提交回复
热议问题