Over a million developers have joined DZone.

Detecting Java Race Conditions With Tests Part 2: Non-Atomic Updates

DZone's Guide to

Detecting Java Race Conditions With Tests Part 2: Non-Atomic Updates

If you update a field from different threads, you must make sure the field isn't updated by one thread between the read and write of another. This article shows how you can test it.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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?

Example of a Test

Let us look at an example of an incorrect synchronized class:

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:

public class TestAccount {
private final Account account = new Account();
        private final static int THREAD_COUNT = 2;

public void testAdd() {
account.setAmount(  account.getAmount() + 20  );

public void chechBalance()
assertEquals( "" , THREAD_COUNT * 20 , account.getAmount()  ); 


This JUnit test uses concurrent-junit to run the test in parallel. The test sometimes succeeds, 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:

Java Race Condition Non Atomic Update

The Solution: Waitpoints

For a test this is rather inconvenient. If a test fails, which is bad enough, it should at least always fail. To achieve this, a thread needs to wait for the other threads before calling the set method. In vmlens this can be done by using a “waitpoint.” You can set waitpoints at the beginning of a monitor block or a volatile field access: If we set the waitpoint at the synchronized block of the set method the test always fails:

vmlens Waitpoint


In the first part you have seen how to detect lost updates with tests. This second part shows how to detect non-atomic updates. In the next part we will see, how to use this technique to test for thread safety. If you have any questions or remarks please comment below.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}