Implement a multithreaded task executor with semaphores
SoFiSoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of concurrent programming, thread-safety, semaphore-style resource management, exception-safe permit release, and extensible API design, and it falls under the Coding & Algorithms category testing concurrency/multithreading, synchronization primitives, and resource management.
Design and implement a thread-safe TaskExecutor that limits concurrent work using a semaphore-like mechanism.
You are given an interface similar to:
initialize(int maxThreads): sets up the executor with a maximum number of “worker permits”.acquire(int permits): blocks until the requested number of permits is available, then reserves them.execute(Task task, int input): runs a task while respecting the permit limit.
A Task is an interface and multiple subclasses implement different behaviors, but all must use the same interface. Each task declares:
- how many threads/permits it requires (e.g.,
requiredPermits()), and - whether
execute(...)should block until the task finishes (blocking) or return immediately while the task continues in the background (fire-and-forget).
Example tasks:
MultiplyTask(factor, xPermits): multipliesinputbyfactor, requiresxPermits, and is fire-and-forget (i.e.,executeshould not wait for completion).DivideTask(divisor, yPermits): dividesinputbydivisor, requiresyPermits, and is blocking (i.e.,executereturns only after completion and returns the computed result).
Requirements:
- Total permits in use across all running tasks must never exceed
maxThreads. - Permits must be released reliably even if a task throws.
- The design should be extensible/maintainable: adding a new
Tasktype should not require changingTaskExecutorlogic beyond using the commonTaskinterface. - Avoid busy-waiting; use proper concurrency primitives.
Specify the key classes/interfaces and implement the core logic of initialize, acquire, and execute (language: Java or pseudocode acceptable).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.