SSW Foursquare

Do you use local copies to resolve race condition?

Last updated by Sylvia Huang [SSW] 5 months ago.See history

Code that looks perfectly fine in a single-threaded scenario could be vulnerable to race condition when some value is shared among multiple threads.

Examine the following if-statement:

if (A is null || (A.PropertyA == SOME_CONSTANT && B))
{
   // some logic
}

Figure: Bad example - Vulnerable to race condition

When the above code is run single-threaded, the second part of the if-condition would never be reached when A is null. However, if A is shared among multiple threads, the value of A could change from not null to null after passing the first check of if-condition, resulting in a NRE in the second check of if-condition.

In order to make the code thread-safe, you should make a local copy of the shared value so that value change caused by another thread would no longer lead to crash.

var copyA = A?.PropertyA;

if (A is null || (copyA == SOME_CONSTANT && B))
{
   // some logic
}

Figure: Good example - Local copy to resolve race condition

We open source. Powered by GitHub