ColdFusion Singletons Revisited
My last article on singletons got a few comments on blogs and in email including how it could be improved (thanks Michael) and a few questions. I also omitted the code showing how the singletons were created and called (now added).
So here's the new improved code!
TweetBacks
http://cfinternals.typepad.com/blog/2007/04/more_s...
A potential race condition exists with the above code, however it would only occur if the application variable doesn't exit and you get perfectly simultaneous requests. (ie once in a blue moon). Even if it does occur and two instances are created the same single instance is returned from the function as the application variable is returned rather than 'this'. ie the code works correctly.
For most requests (where the application variable exists) a race condition doesn't exist so adding a lock may be adversely affect performance by effectively making the code single threaded.
I also note that you added a "remove" method so the singleton could be recreated. Depending upon circumstances, the number of singletons, and how often that function is called, "blue moons" could occur more often that one might think, especially on a server under heavy load.
All in all, I think it's best to program defensively, and sinply ensure that the bug never has a chance to appear. And since the lock is inside the if test and should only occur once on object creation, the performance aspect is negligible.
I did like deleting the function reference. Neat trick. Adding function references is fun too...
Instead of deleting it wouldn't you need to do something like: instance.invalid=instance.valid; setting the "invalid" function to a safe one so initialization can proceed to completion?
If you can do the locking in such as way that it doesn't have an effect on performance then yes it should be added. It may be that later on changes to the code does make the race condition have negative side effects and these issues are very hard to debug/track down.
Glad you liked the removal of methods via structdelete still not 100% sure I'd actually use it in a production system but I'm sure it could be useful under other circumstances.
Originally I was checking to see if the method existed before calling it but once I found it wasn't needed I removed the checks to make the code simpler.
Now you might say ... just scope the class to SESSION... but not really a way to go in my books.
Generally I place the instance in the application scope that way it a singleton for the entire application. If it was placed in the session scope it would be a singleton for that users session, which can also be useful in some situations.