Little Pattern: Message-Based Loop

Occasionally the question comes up: how do I have my actor perform a costly calculation but keep it “cancelable”. The reason for this request is usually that calculations are started in parallel and then the first successful result is used and all others discarded. But if the actor is busy processing, how do I tell it to stop?

The message-based loop shown above keeps the actor responsive by continuing “through the mailbox” from time to time. And if a StopIt message happens to have been enqueued in the meantime, all work is aborted. This shows of course only the minimalistic essence of the pattern, real use-cases will have to embed this in proper supervision hierarchies and dispatch the Work and StopIt messages through a coordinating master actor.

Recent comments

Blog comments powered by Disqus