Last week, I brought up class Promise, which makes it easy to code a long running task in a linear fashion - but I just referenced a screencast on it. Today I thought I'd mention how I use Promise in this blog server.
On the sidebar, there's a search box for the blog. Back in the server, this is what actually happens:
promise := [self
actuallySearchFor: searchText
inTitle: searchInTitle
inText: searchInText] promiseAt: Processor userBackgroundPriority.
allResults := promise value.
"other code here"
The search executes as soon as #promiseAt: is sent, but the rest of the method is held up pending the results (queried for by #value) - it's like forking a process and then waiting on a Semaphore, except that all of those mechanics have been wrapped up nicely for you. It makes it very easy to code things that need to happen in a linear fashion, but that you would like to just toss into a different process. As the class comment says:
A Promise represents a value that is being computed by a concurrently executing process. An attempt to read the value of a Promise will wait until the process has finished computing it. If the process terminates with an exception, an attempt to read the value of the Promise will raise the same exception.
Technorati Tags:
promise, futures