Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active March 16, 2017 22:13
Show Gist options
  • Save soverby/611f6b7e1787b0019c1e1a9bd7acbf6f to your computer and use it in GitHub Desktop.
Save soverby/611f6b7e1787b0019c1e1a9bd7acbf6f to your computer and use it in GitHub Desktop.
I needed a way to throttle an executor so I didn't overload a receiver (ElasticSearch - doing multi-threaded bulk updates to it).
package com.soverby.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;
public class ThrottledExecutor {
private static final int MAX_AVAILABLE = 5;
private final ExecutorService service = Executors.newFixedThreadPool(3);
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
private final ReentrantLock runLock = new ReentrantLock();
public static void main(String[] args) {
ThrottledExecutor executor = new ThrottledExecutor();
executor.go();
}
public void go() {
runLock.lock();
Thread permitDrainer = new Thread() {
@Override
public void run() {
do {
try {
System.out.println("PermitDrainer waiting...");
Thread.sleep(10000);
available.release(MAX_AVAILABLE);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
} while (runLock.isLocked());
System.out.println(" permitDrainer ending");
}
};
permitDrainer.start();
IntStream.range(0, 25).forEach(i -> {
try {
available.acquire();
System.out.println(" submitting " + i);
service.submit(() -> {
try {
Thread.sleep(1000);
System.out.println(" completing " + i);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
});
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
});
runLock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment