|
Architect or Cobbler?
Good code starts with good design |
|
about me
links
Blogs I follow
recent posts
archives
feeds |
The One and OnlySunday, August 28, 2005Probably one of the most common patterns you'll come accross is the singleton pattern, where you want to ensure you only have one object in an AppDomain. The easiest way to ensure this is quite simple: For instance if you want to ensure there is only ever one King, you'll write something like this: Which is probably OK for 90% of applications. But what if the King was an overweight bloated object, you may want to support lazy initialization. In this case you will have to acquire locks because multiple clients may request TheOneAndOnly at the same time, so your code may look something like this: This is as safe as houses, but not particularly performant. Every client requiring access to TheOneAndOnly will aqcuire a lock, even though once the object is created it is not necessary. To fix this consider using a double locking pattern, like this. You may have heard that the double locking pattern can't be relied on, as write ordering is not guaranteed. To a certain extent this is correct, however on the X86 architecture write ordering is guaranteed, so this is acceptable. On other architectures, or on multiple CPU systems you may want to force a synchronization by using the MemoryBarrier method. This code is safe on all architectures, for the small expense of a single extra synchronization. You would think that that's it, however there is one more problem. Serialization may cause some problems. Mark TheKing as Serializable and run the following code. Clearly there are now two Elvises. Deserializing the object has allowed the subtle creation of a new Elvis object. To fix this you need to take charge of the Serialization and Deserialization process. Your code for your TheKing object will now look something like this So there you have it, a lazily initialized, thread safe Serializable Elvis. I bet you didn't think it would be that much work when you started reading the blog. # posted by James @ 2:44 PM Tomorrow never comesFriday, August 26, 2005You stop blogging for a few days, and before you know it months have gone by. I blame one of my colleagues, who read my blog and started calling me "Geek Boy", but if the truth be known it's bone idleness that's the root cause of the malaise. Anyway Dave was upbraiding me last night (at the pub again, for some strange reason) - so in a fit of contrition, I am resolving to start blogging again. So check in over the next few days and Geek Boy should be fully back in action. # posted by James @ 4:24 PM |
|
|
|