Skip to content

Instantly share code, notes, and snippets.

@thefourtheye
Created April 5, 2025 17:39
Show Gist options
  • Save thefourtheye/0b569a4627d456f5fb096259e62ffe2a to your computer and use it in GitHub Desktop.
Save thefourtheye/0b569a4627d456f5fb096259e62ffe2a to your computer and use it in GitHub Desktop.
Fun with Executor
package in.thefourtheye;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
final int CORE_POOL_SIZE = 1;
final int MAX_POOL_SIZE = 5;
final long KEEP_ALIVE_TIME_IN_MS = 1000;
final int MAX_CAPACITY = 100;
final ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME_IN_MS, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(MAX_CAPACITY)
);
final CountDownLatch latch = new CountDownLatch(1);
executor.execute(new ParentTask(latch, executor));
await(latch);
executor.shutdownNow();
}
static class ChildTask implements Runnable {
private final CountDownLatch latch;
public ChildTask(final CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
latch.countDown();
print("ChildTask");
}
}
static class ParentTask implements Runnable {
private final CountDownLatch latch;
private final Executor executor;
ParentTask(final CountDownLatch latch, final Executor executor) {
this.latch = latch;
this.executor = executor;
}
@Override
public void run() {
print("ParentTask");
final CountDownLatch childTaskLatch = new CountDownLatch(1);
executor.execute(new ChildTask(childTaskLatch));
await(childTaskLatch);
latch.countDown();
}
}
static void print(final String msg) {
System.out.printf("[%s] [%s]\n", Thread.currentThread().getName(), msg);
}
static void await(final CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment