Do you use local copies to resolve race condition?

Updated by Brady Stroud [SSW] 1 year ago. See history

123
<introEmbed body={<> 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: 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: Figure: Good example - Local copy to resolve race condition

Acknowledgements

Sylvia Huang
Related rules

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star