I just realized that in a gcol environment, lazy creation may not always need locks…

…where you’re doing lazy construction of something that is an immutable singleton. If creating more than one isn’t an issue (and since the object created is fixed it shouldn’t generally be) then the creation /initialization race isn’t relevant.

The garbage collector will clean up any duplicates that get made. The callers will have valid objects until they’re done. Whichever object gets stored last will become the object that is served to all subsequent customers.

This avoids the costs of locking a mutex (or something similar) and should result in simpler code. Once you have established the static reference, all subsequent requests just get that object.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.