Race Conditions

Race Conditions

A race condition or race hazard is the behavior of an electronic, software or other system where the output is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended. wikipedia

There are two types of race conditions:

Field access which is not synchronized according to the java memory model

The outcome depends on the hardware architecture and the order the threads are accessing the field. vmlens automatically detects this type of race conditions.vmlens shows those race conditions in the Race Conditions View.

@RunWith(ConcurrentTestRunner.class)
public class RaceConditionMissingSynchronization {


private MutableInt mutableInt = new MutableInt();

@Test
public void addOne()
{
	mutableInt.add(1);
}

}

You can download the class here RaceConditionMissingSynchronization.java

vmlens race conditions view

The picture shows the vmlens Race Conditions View.

Outcome depends on the order the threads are accessing the field

The field is synchronized according to the java memory model but the outcome still depends on the order the threads are accessing the field.

@RunWith(ConcurrentTestRunner.class)
public class RaceConditionVolatileCounter {


private volatile int i = 0;

@Test
public void addOne()
{
	i++;
}

@After
public void assertCount()
{
	assertEquals("4 Threads running addOne in parallel should lead to 4" , 4 , i);
}
}

vmlens race conditions view

The picture shows the vmlens Access Details View with waitpoints.

To find this type of race conditions use waitpoints at the volatile fields and monitors.

Related References