CodeQL queries 1.24
Double-checked locking requires that the underlying field is
otherwise the program can behave incorrectly when running in multiple threads,
for example by computing the field twice.
There are several ways to make the code thread-safe:
- Avoid double-checked locking, and simply perform everything within the lock statement.
- Make the field volatile using the
- Use the
System.Lazyclass, which is guaranteed to be thread-safe. This can often lead to more elegant code.
The following code defines a property called
Name, which calls the method
LoadNameFromDatabase the first time that the property is read, and then
caches the result. This code is efficient but will not work properly if the property
is accessed from multiple threads, because
be called several times.
A common solution to this is double-checked locking,
which checks whether the stored value is
null before locking the mutex.
This is efficient because it avoids a potentially expensive lock operation if a
value has already been assigned to
However this code is incorrect because the field
volatile, which could result in
name being computed twice on some systems.
The first solution is to simply avoid double-checked locking (Recommendation 1):
Another fix would be to make the field volatile (Recommendation 2):
It may often be more elegant to use the class
System.Lazy, which is
automatically thread-safe (Recommendation 3):