Futures advent day 20

Day 20 - Automatic Cancellation

A few days ago we saw two similar ways to combine a list of futures into a single future; needs_all and needs_any. In both of these combinations it can happen that the combined future has its result determined before all of its components are ready - needs_all if any component fails, or needs_any if any component is successful. In that case there is no need to continue running the remaining operations, as their outcome cannot further influence the combination.

Yesterday we saw how futures support a cancel operation which cascades back up the tree of operations, causing individual components of an action to be cancelled, and generally all the operations halted. Naturally, both needs_all and needs_any will do this when they are cancelled, causing all of their still-pending components to be cancelled. But additionally, both will cancel remaining pending futures automatically when their result is already known. needs_all will cancel any futures that remain pending when it has to fail because a component failed, and needs_any will cancel any that remain when it already has a result.

For example, recalling day 13 where we first saw needs_all:

my $f = Future->needs_all(
  GET( "http://my-site-here.com/page1" ),
  GET( "http://my-site-here.com/page2" ),
  GET( "http://my-site-here.com/page3" ),

my @pages = $f->get;

As was mentioned before, if any of these page fetches fails then the overall operation will fail too, and the get method will throw this exception. What wasn't mentioned before is that since at this point any other pending fetch operations have no further bearing on the result of the combined future, there is no need to continue running them. In this situation needs_all will cancel them.

<< First | < Prev | Next >

No comments:

Post a Comment