@Test public void limitsNumberOfForwardedTasks() throws InterruptedException { Semaphore completedTasks = new Semaphore(0); int maximumConcurrency = 10; CountingExecutor countingExecutor = new CountingExecutor(); ThrottledForwardingExecutor throttledExecutor = new ThrottledForwardingExecutor(maximumConcurrency, countingExecutor); int numTasks = maximumConcurrency + 1; CountDownLatch schedulingLatch = new CountDownLatch(1); for (int i = 0; i < numTasks; ++i) { int currentTask = i; throttledExecutor.execute( () -> { try { if (currentTask < maximumConcurrency) { schedulingLatch.await(); } completedTasks.release(); } catch (InterruptedException e) { fail("Unexpected InterruptedException: " + e); } }); } schedulingLatch.countDown(); completedTasks.acquire(numTasks); assertEquals(maximumConcurrency, countingExecutor.getNumTasks()); }
@Override public void execute(Runnable command) { if (availableSlots.tryAcquire()) { try { executor.execute( () -> { command.run(); availableSlots.release(); }); } catch (RejectedExecutionException e) { command.run(); } } else { command.run(); } }
ThrottledForwardingExecutor implements Executor { @Override public void execute(Runnable command) { if (availableSlots.tryAcquire()) { try { executor.execute( () -> { command.run(); availableSlots.release(); }); } catch (RejectedExecutionException e) { command.run(); } } else { command.run(); } } }
ThrottledForwardingExecutor implements Executor { @Override public void execute(Runnable command) { if (availableSlots.tryAcquire()) { try { executor.execute( () -> { command.run(); availableSlots.release(); }); } catch (RejectedExecutionException e) { command.run(); } } else { command.run(); } } ThrottledForwardingExecutor(int maximumConcurrency, Executor executor); }
ThrottledForwardingExecutor implements Executor { @Override public void execute(Runnable command) { if (availableSlots.tryAcquire()) { try { executor.execute( () -> { command.run(); availableSlots.release(); }); } catch (RejectedExecutionException e) { command.run(); } } else { command.run(); } } ThrottledForwardingExecutor(int maximumConcurrency, Executor executor); @Override void execute(Runnable command); }
ThrottledForwardingExecutor implements Executor { @Override public void execute(Runnable command) { if (availableSlots.tryAcquire()) { try { executor.execute( () -> { command.run(); availableSlots.release(); }); } catch (RejectedExecutionException e) { command.run(); } } else { command.run(); } } ThrottledForwardingExecutor(int maximumConcurrency, Executor executor); @Override void execute(Runnable command);  }