[concurrency-interest] Exception handling with ParallelArray

Doug Lea dl at cs.oswego.edu
Fri Dec 28 07:20:12 EST 2007


Trevor Kramer wrote:
> If I am using ParallelArray.apply and am doing something inside the
> apply() that throws a checked exception (that I have to catch since
> Ops.Procedure doesn't throw exceptions) is there a standard way to get
> that exception out to the calling thread?
> 

If you really need to do this (see below),
the (messy) recommended strategy is to tunnel it as
an unchecked exception. For example, if you make a call
to method f() that can throw some checked exception Ex,
you can declare:
   class TrappedEx extends RuntimeException {
      TrappedEx(Ex cause) { super(cause); }
   }
and then inside the Procedure do
   try {
      f();
   } catch(Ex ex) {
     throw new TrappedEx(ex);
   }
And the surround the ParallelArray.apply:
   try {
      pa.apply(theProcedure);
   } catch(TrappedEx ex) {
      // handle it
   }

There are a few reasons we force you to do this:

1. In practice, the majority of Checked Exceptions are defined
   for operations like IO that don't belong in forkjoin
   computations anyway.

2. While we internally perform the cleanup and cancellation
   across parallel threads executing the apply when any one of them
   encounters an exception, we can't supply
   any points at which you can locally handle the exception until
   they complete, at which point any encountered (unchecked) exception
   is rethrown. (Of course, if you can locally handle the
   exception inside the Procedure, you don't need any of this anyway.)

3. Until/unless better support for disjunctive exception types
   emerges, we can't nicely support methods that allow arbitrary
   combinations of exceptions on Procedures etc, except by using
   the Callable strategy which permits any exception. Which people
   have grown to dislike, because it forces you to place try/catch
   blocks around every call, even if you know that no handleable
   exceptions are thrown. (Which in turn leads people to use empty
   catches, which are much worse than not catching at all.) Given
   (1) and (2) above though, it seems unlikely that we'd include
   support for fancier exception types even if it becomes available.


-Doug




More information about the Concurrency-interest mailing list