I have fields that manage information that multiple threads potentially work with. Access to these fields is critical so I instantiated a semaphore:
Semaphore semaphore = new Semaphore(1);
Every method tries to acquire the semaphore, essentially locking if none is available:
public void method()
{
semaphore.acquire();
doStruff();
cleanUp()
}
//Other methods using the same basic layout as the method above.
public void cleanUp()
{
//watch for state consistency and do some clean up
semaphore.release();
}
How would I go about testing the above knowing that:
- I don't want to use timed testing, using
Thread.sleep(x)
due to the inherent problems with that method such as the dependence on the clock and lack in trust of that method. - I cannot use MultithreadedTC, at least not that I know of, since one thread will always be executing, hence, the metronome won't advance to the next tick.
- I don't want to modify existing code to add bits just for testing purposes. The code should stay clear of additions from testing.
- I would want something solid that I can run multiple times and use in regression testing.
- As I am not the only one using the code, it should be Java native and not use a scripting language such as ConAn.
The bit of code is small enough that I can, with a good certainty, say that it won't deadlock or the condition detailed above violated. However, a good test case could lend more weight to it and certainly add more confidence.