In C#, the following code (from this page) can be used to lazily instantiate a singleton class in a thread safe way:
class Foo {
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
lock(this) {
if (helper == null)
helper = new Helper();
}
}
return helper;
}
}
What would be the equivalent thread safe Delphi code?
The article also mentions two problems with Double Checked Locking in Java:
- it is possible that the new object is constructed before the helper reference is made to point at the newly created object meaning that two objects are created
- it is possible that the helper reference is made to point at a block of memory while the object is still being created meaning that a reference to an incomplete object will be returned
So while the code of the C# and the Java version in the mentioned article look almost identical, only the C# version works as expected. Which leads to the additional question if these two problems also exist in a Delphi version of Double-Checked Locking?