Advertisement
tpeierls

BoundedExecutorService

Feb 8th, 2012
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.94 KB | None | 0 0
  1. /*
  2.  * This code is placed in the public domain by its author, Tim Peierls.
  3.  */
  4. package com.example.bqe;
  5.  
  6. import java.util.List;
  7.  
  8. import java.util.concurrent.AbstractExecutorService;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.RejectedExecutionException;
  11. import java.util.concurrent.Semaphore;
  12. import java.util.concurrent.TimeUnit;
  13.  
  14.  
  15. /**
  16.  * Wrapper for ExecutorService that imposes a hard bound on the number of
  17.  * running tasks, rejecting submissions when the bound is reached. This may
  18.  * be appropriate when the wrapped service has no bound on pool size and
  19.  * you want to limit thread creation (and you are willing to have tasks
  20.  * rejected at submission time in order to enforce that limit).
  21.  */
  22. public class BoundedExecutorService extends AbstractExecutorService {
  23.  
  24.     public BoundedExecutorService(ExecutorService exec, int permits) {
  25.         this.exec = exec;
  26.         this.sem = new Semaphore(permits); // fairness irrelevant here
  27.     }
  28.  
  29.     @Override public void execute(final Runnable runnable) {
  30.         if (!sem.tryAcquire()) {
  31.             throw new RejectedExecutionException("Too many tasks running.");
  32.         }
  33.         exec.execute(new Runnable() {
  34.             public void run() {
  35.                 try {
  36.                     runnable.run();
  37.                 } finally {
  38.                     sem.release();
  39.                 }
  40.             }
  41.         });
  42.     }
  43.  
  44.     @Override public boolean isTerminated() { return exec.isTerminated(); }
  45.     @Override public boolean isShutdown() { return exec.isShutdown(); }
  46.     @Override public List<Runnable> shutdownNow() { return exec.shutdownNow(); }
  47.     @Override public void shutdown() { exec.shutdown(); }
  48.     @Override public boolean awaitTermination(long timeout, TimeUnit unit)
  49.             throws InterruptedException {
  50.         return exec.awaitTermination(timeout, unit);
  51.     }
  52.  
  53.     private final ExecutorService exec;
  54.     private final Semaphore sem;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement