java - How to write unit tests that tests concurrency invariants -
java - How to write unit tests that tests concurrency invariants -
there other questions issue, i'm trying figure how approach unit testing this:
public class semaphore extends lock { private atomicinteger semaphore = new atomicinteger(0); public synchronized boolean available() { homecoming semaphore.intvalue() == 0; } public synchronized void acquire() { semaphore.incrementandget(); } public synchronized void release() { semaphore.decrementandget(); } }
this homespun locking mechanism (just learning purposes). how test thread safety of this? know there no guarantees when comes unit testing concurrent code, how go writing unit test attempts test obvious invariants inherent in locking mechanism?
i guess i'll reply own question since did research. there's great framework called multithreadedtc. allows set tests so:
public class safesemaphoretest extends multithreadedtestcase { private safesemaphore semaphore; atomicinteger ai = new atomicinteger(0); @override public void initialize() { semaphore = new safesemaphore(); } public void thread1() throws interruptedexception { asserttick(0); semaphore.acquire(); waitfortick(2); asserttick(2); semaphore.acquire(); assertequals(semaphore.getvalue(), 2); assertequals(semaphore.getvalue()==3, false); semaphore.release(); semaphore.release(); } public void thread2() throws interruptedexception { waitfortick(1); asserttick(1); assertequals(semaphore.available(), false); waitfortick(3); asserttick(3); assertequals(semaphore.available(), true); } }
where waitfortick(int) calls create current thread block until tick reached. there development create bit more modern improve junit integration: http://janvanbesien.blogspot.com/2009/06/modernizing-multithreadedtc-junit-4.html
java unit-testing
Comments
Post a Comment