July 27, 2016
If you update a field from different threads, you must make sure that between the read and the write from one thread the field is not updated by another thread. You can achieve this by using a synchronized block or the atomic compareAndSet method. But how can you test it?
class Account { private int amount = 0; public synchronized int getAmount() { return amount; } public synchronized void setAmount(int amount) { this.amount = amount; } }To test this class we use the following junit test case:
@RunWith(ConcurrentTestRunner.class) public class TestAccount { private final Account account = new Account(); private final static int THREAD_COUNT = 2; @Test @ThreadCount(THREAD_COUNT) public void testAdd() { account.setAmount( account.getAmount() + 20 ); } @After public void chechBalance() { assertEquals( "" , THREAD_COUNT * 20 , account.getAmount() ); } }This junit test uses concurrent-junit to run the test in parallel. The test sometimes succeed, sometimes fails. Every time the get method is called immediately one after the other the sum is incorrect. In the vmlens Method Explorer you can see the order of the two methods. In case of an error you will see the following:
© 2020 vmlens Legal Notice Privacy Policy