Optimistic Locking For Retrieving Result Sets
I’m in the middle of updating my Silverlight code to use asynchronous HTTP requests — fortunately, I spent last summer writing a GWT application, where HTTP requests have always been asynchronous, so I’ve got a library of patterns for solving common problems.
For instance, suppose that you’re doing a search, and then you’re displaying the result of the search. The most reliable way to do this is to use Pattern Zero, which is, do a single request to the server that retrieves all the information — in that case you don’t need to worry about what happens if, out of 20 HTTP requests, one fails.
Sometimes you can’t redesign the client-server protocol, or you’d like to take advantage of caching, in which case you might do something like this (in psuedo code):
getAListOfResults(new AsyncCallback {
... clearGUI();
foreach(result as item) {
fetchItem(item,new AsyncCallback {
... addItemToGui()
}
}
First we retrieve a list of items, then we retrieve information about each item: this is straightforward, but not always reliable. Even if your application runs in a single thread, as it would in GWT or if you did everything in the UI thread in Silverlight, you can still have race conditions: for instance, results can come back in a random order, and getAListOfResults() can be called more than once by multiple callbacks — that’s really the worst of the problems, because it can cause results to appear more than once in the GUI.
There are a number of solutions to this problem, and a number of non-solutions. A simple solution is to make sure that getAListOfResults() never gets called until the result set has come back. I was able to do that for quite a while last summer, but the application finally reached a level of complexity where it was impossible… or would have required a major redesign of the app. Another is to use pessimistic locking: to not let getAListOfResults() run while result sets are coming back — I think this can be made to work, but if you’re not careful, your app can display stale data or permanently lock up.
Fortunately there’s a pattern to retrieve result sets using optimistic locking that displays fresh data and can’t fail catastrophically
Paul Houle on April 4th 2008 in Asynchronous Communications, Dot Net, GWT, Java, Silverlight
![[Generation Five]](/q/wp-content/themes/mach-go/images/GenerationFive.png)
![[Reliable And Maintainable Software For The Next Generation]](/q/wp-content/themes/mach-go/images/ReliableAndMaintainableSoftwareForTheNextGeneration.png)

