public Result [ ] executeAndWait ( Command [ ] commands ) { Result [ ] results = new Result [ commands . length ] ; if ( numProcessors == 1 ) { // optimize for one processor for ( int i = 0 ; i < commands . length ; i ++ ) { Object obj = null ; InvocationTargetException ex = null ; try { obj = commands [ i ] . call ( ) ; } catch ( Exception e ) { ex = new InvocationTargetException ( e ) ; } results [ i ] = new Result ( obj , ex ) ; } } else { FutureResult [ ] futures = new FutureResult [ commands . length ] ; for ( int i = 0 ; i < commands . length ; i ++ ) { final Command c = commands [ i ] ; futures [ i ] = new FutureResult ( ) ; Runnable r = futures [ i ] . setter ( new Callable ( ) { public Object call ( ) throws Exception { return c . call ( ) ; } } ) ; try { executor . execute ( r ) ; } catch ( InterruptedException e ) { // run with current thread instead r . run ( ) ; } } // wait for all results boolean interrupted = false ; for ( int i = 0 ; i < futures . length ; i ++ ) { Object obj = null ; InvocationTargetException ex = null ; for ( ; ; ) { try { obj = futures [ i ] . get ( ) ; } catch ( InterruptedException e ) { interrupted = true ; // reset interrupted status and try again Thread . interrupted ( ) ; continue ; } catch ( InvocationTargetException e ) { ex = e ; } results [ i ] = new Result ( obj , ex ) ; break ; } } if ( interrupted ) { // restore interrupt status again Thread . currentThread ( ) . interrupt ( ) ; } } return results ; }
Executes a set of commands and waits until all commands have been executed . The results of the commands are returned in the same order as the commands .