|
Architect or Cobbler?
Good code starts with good design |
|
about me
links
Blogs I follow
recent postsarchives
feeds |
The One and OnlySunday, August 28, 2005
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 << Main blog page |
|
|
|