Build a Bounded Permit Task Execution Engine
Data Structure DesignModel answerLast updated
Implement a concurrency manager that controls variable permit usage per task, supports blocking and asynchronous execution, and guarantees safe permit releases.
Design and implement a thread-safe task management component, TaskExecutor, that constrains concurrent processing using variable resource tokens (permits).
Requirements
- Permit Pool Initialization:
initialize(int maxPermits)sets up the system with a total capacity of concurrent permits.- Re-initialization should be rejected if active permits are currently checked out.
- Resource Allocation:
acquire(int permits)blocks the calling thread without busy-waiting until the specified number of permits are available, then reserves them.release(int permits)returns the permits back to the execution engine and wakes up waiting threads.- Requests exceeding
maxPermitsmust fail immediately to prevent unconditional deadlocks.
- Polymorphic Task Contract (
ExecutableTask):getRequiredPermits(): Returns the positive integer count of permits needed.isBlocking(): Returnstrueifexecute(...)must block until completion and return the direct result, orfalseif it should execute asynchronously in the background.run(T input): Performs the domain logic on the given input.
- Execution Engine (
execute):execute(ExecutableTask task, T input)acquires the needed permits before starting the task (providing natural backpressure).- If the task is blocking, it runs in the caller's thread, releases its permits upon completion (even if an exception occurs), and returns the result.
- If the task is non-blocking (asynchronous), permit ownership is transferred to a background worker thread. The caller receives a handle (such as a
Futureor equivalent deferred handle) immediately while the background thread releases permits upon task completion or failure.
- Robustness & Extensibility:
- Permit allocation and release must be exception-safe (no resource leaks).
- The engine must strictly depend on the
ExecutableTaskinterface so that adding new task types does not require modifyingTaskExecutor.
Provide an object-oriented implementation in Java or Python detailing the core interfaces and the TaskExecutor implementation.
Hints
Hint 1
Use explicit locks and condition variables (or standard synchronization primitives) to avoid spin-locking when waiting for available permits.
Hint 2
Consider thread safety during permit handoff for asynchronous tasks: if background thread creation fails after permits are acquired, make sure permits are released immediately in the submission thread.
Hint 3
When broadcasting availability during `release()`, ensure all waiting threads are notified (`notifyAll` / `notify_all`), because different callers may be waiting for different permit quantities.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
The core challenge involves managing multi-permit allocation across concurrent tasks while seamlessly handling both synchronous (blocking) and asynchronous (fire-and-forget) task semantics.
The solution relies on three key design concepts:
- Counting Monitor / Custom Semaphore: A custom synchronization manager uses a lock and condition variable (
Condition/Lock) to maintain the available permit count. Threads requesting $N$ permits block on the condition variable untilavailable >= N. UsingnotifyAll()instead ofnotify()ensures that threads waiting for smaller permit allocations are not blocked by a single thread waiting for a larger permit allocation. - Unified Interface (
ExecutableTask): Decouples the executor logic from specific task behaviors. The executor relies exclusively ongetRequiredPermits(),isBlocking(), andrun(). - Execution & Resource Lifecycle Management:
- Blocking tasks: Permits are acquired by the calling thread, execution takes place inside a
try-finallyblock on the same thread, and permits are freed in thefinallyblock before returning the result. - Asynchronous tasks: Permits are acquired on the caller's thread before task submission (creating backpressure). Once acquired, permit ownership transfers to a background worker. A
try-finallyblock inside the background worker ensures permits are released even if the task fails. If dispatching the background thread fails (e.g., due to system resource exhaustion), the submission thread catches the error, releases the permits, and re-throws the exception.
- Blocking tasks: Permits are acquired by the calling thread, execution takes place inside a
Implementation (Java)
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
// Unified interface for all polymorphic tasks
public interface ExecutableTask<I, O> {
int getRequiredPermits();
boolean isBlocking();
O run(I input) throws Exception;
}
// Sample Concrete Task 1: Non-blocking task
public class MultiplyTask implements ExecutableTask<Integer, Integer> {
private final int factor;
private final int permits;
public MultiplyTask(int factor, int permits) {
this.factor = factor;
this.permits = permits;
}
@Override
public int getRequiredPermits() { return permits; }
@Override
public boolean isBlocking() { return false; }
@Override
public Integer run(Integer input) {
return input * factor;
}
}
// Sample Concrete Task 2: Blocking task
public class DivideTask implements ExecutableTask<Double, Double> {
private final double divisor;
private final int permits;
public DivideTask(double divisor, int permits) {
this.divisor = divisor;
this.permits = permits;
}
@Override
public int getRequiredPermits() { return permits; }
@Override
public boolean isBlocking() { return true; }
@Override
public Double run(Double input) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero");
}
return input / divisor;
}
}
// Main Concurrency Control & Execution Engine
public class TaskExecutor {
private final Lock lock = new ReentrantLock();
private final Condition permitsAvailable = lock.newCondition();
private final ExecutorService asyncPool = Executors.newCachedThreadPool();
private int maxPermits;
private int availablePermits;
private boolean initialized = false;
public void initialize(int maxPermits) {
if (maxPermits <= 0) {
throw new IllegalArgumentException("Permit capacity must be positive.");
}
lock.lock();
try {
if (initialized && availablePermits != this.maxPermits) {
throw new IllegalStateException("Cannot re-initialize while active permits are checked out.");
}
this.maxPermits = maxPermits;
this.availablePermits = maxPermits;
this.initialized = true;
permitsAvailable.signalAll();
} finally {
lock.unlock();
}
}
public void acquire(int permits) throws InterruptedException {
lock.lock();
try {
if (!initialized) {
throw new IllegalStateException("Executor is not initialized.");
}
if (permits > maxPermits) {
throw new IllegalArgumentException("Requested permits (" + permits +
") exceeds maximum capacity (" + maxPermits + ").");
}
while (availablePermits < permits) {
permitsAvailable.await();
}
availablePermits -= permits;
} finally {
lock.unlock();
}
}
public void release(int permits) {
lock.lock();
try {
if (availablePermits + permits > maxPermits) {
throw new IllegalStateException("Released permits exceed maximum pool limit.");
}
availablePermits += permits;
permitsAvailable.signalAll();
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
public <I, O> Object execute(ExecutableTask<I, O> task, I input) throws Exception {
int required = task.getRequiredPermits();
acquire(required);
if (task.isBlocking()) {
try {
return task.run(input);
} finally {
release(required);
}
} else {
// Asynchronous Execution Path
CompletableFuture<O> future = new CompletableFuture<>();
try {
asyncPool.submit(() -> {
try {
O result = task.run(input);
future.complete(result);
} catch (Throwable t) {
future.completeExceptionally(t);
} finally {
release(required);
}
});
} catch (Exception dispatchException) {
// If thread submission fails, clean up permits immediately
release(required);
throw dispatchException;
}
return future;
}
}
public void shutdown() {
asyncPool.shutdown();
}
}
Complexity Analysis
- Time Complexity:
acquire(k)/release(k): $O(1)$ state updates under the monitor lock. Releasing permits invokessignalAll(), waking $W$ waiting threads to re-evaluate their predicates, incurring an $O(W)$ broadcast cost.execute(...): $O(1)$ dispatch overhead plus the time complexity of the underlyingtask.run(input).
- Space Complexity:
- Auxiliary memory per executor is $O(1)$ for lock primitives, plus $O(T)$ in memory for $T$ concurrent active background worker threads/futures bounded by
maxPermits.
- Auxiliary memory per executor is $O(1)$ for lock primitives, plus $O(T)$ in memory for $T$ concurrent active background worker threads/futures bounded by