< prev index next >
   1 package java.net.http;
   2 
   3 import java.util.concurrent.BlockingQueue;
   4 import java.util.concurrent.Executor;
   5 import java.util.concurrent.RejectedExecutionException;
   6 
   7 import static java.util.Objects.requireNonNull;
   8 
   9 //
  10 // Executor that runs one task at a time, though possibly by different threads.
  11 // Tasks are executed in a happen-before order (synced through the queue).
  12 //
  13 final class SequentialExecutor implements Executor {
  14 
  15     private final BlockingQueue<Runnable> tasks;
  16     private final SignalHandler handler;
  17 
  18     SequentialExecutor(Executor executor, BlockingQueue<Runnable> tasks) {
  19         this.tasks = requireNonNull(tasks);
  20         this.handler = new SignalHandler(requireNonNull(executor), this::pollAndExecute);
  21     }
  22 
  23     @Override
  24     public void execute(Runnable command) {
  25         requireNonNull(command);
  26         if (!tasks.offer(command)) {
  27             throw new RejectedExecutionException();
  28         } else {
  29             handler.signal();
  30         }
  31     }
  32 
  33     private void pollAndExecute() {
  34         Runnable t;
  35         while ((t = tasks.poll()) != null) {
  36             t.run();
  37         }
  38     }
  39 }
< prev index next >