Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.73 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Producer Consumer pattern - handling producer failure
  2. // helper class that does the following
  3. //
  4. // if any thread has an exception then interrupt all the others with an eye to cancelling them
  5. // if the thread calling execute() is interrupted then interrupt all the child threads
  6. public class LinkedExecutor
  7. {
  8.     private final Collection<Runnable> runnables;
  9.     private final String name;
  10.  
  11.     public LinkedExecutor( String name, Collection<Runnable> runnables )
  12.     {
  13.         this.runnables = runnables;
  14.         this.name = name;
  15.     }
  16.  
  17.     public void execute()
  18.     {
  19.         ExecutorService executorService = Executors.newCachedThreadPool( ConfigurableThreadFactory.newWithPrefix( name ) );
  20.  
  21.         // use a completion service to poll the results
  22.         CompletionService<Object> completionService = new ExecutorCompletionService<Object>( executorService );
  23.  
  24.         for ( Runnable runnable : runnables )
  25.         {
  26.             completionService.submit( runnable, null );
  27.         }
  28.  
  29.         try
  30.         {
  31.             for ( int i = 0; i < runnables.size(); i++ )
  32.             {
  33.                 Future<?> future = completionService.take();
  34.                 future.get();
  35.             }
  36.         }
  37.         catch ( InterruptedException e )
  38.         {
  39.             // on an interruption of this thread interrupt all sub-threads in the executor
  40.             executorService.shutdownNow();
  41.  
  42.             throw new RuntimeException( "Executor '" + name + "' interrupted", e );
  43.         }
  44.         catch ( ExecutionException e )
  45.         {
  46.             // on a failure of any of the sub-threads interrupt all the threads
  47.             executorService.shutdownNow();
  48.  
  49.             throw new RuntimeException( "Execution execution in executor '" + name + "'", e );
  50.         }
  51.     }
  52. }