AlgoMaster Logo
AlgoMasterDesign a Keyed Task Executormedium

Design a Keyed Task Executor

medium

Design a task executor that uses fine-grained locking to coordinate operations by key.

Implement the KeyedTaskExecutor class:

  • KeyedTaskExecutor(keyCount) creates an executor for keys from 0 through keyCount - 1.
  • execute(key, task) waits for exclusive access to key, then invokes task exactly once before returning.

Tasks submitted with the same key must never overlap. Tasks using different keys must be independent and capable of executing at the same time; an operation on one key must not be blocked solely because another key is busy.

The key's lock must remain held for the callback's entire execution. If task throws an unchecked exception or panics, the lock must still be released and the original failure must continue to the caller.

Different KeyedTaskExecutor instances must also be independent. No fairness or same-key ordering policy is required.

The judge creates all caller threads and supplies the callbacks. Standard concurrency, callback, lock, and thread APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: Both operations use key 1, so they share the same lock. Either task may run first.

Example 2:

Input:

Output:

Explanation: Keys 0 and 2 have separate locks, so neither operation has to wait for the other.

Constraints

  • 1 <= keyCount <= 100
  • 0 <= key < keyCount
  • At most 100 threads use one executor at a time.
  • At most 50000 calls are made per executor.
  • A callback may complete normally or fail with an unchecked exception or panic.
  • A callback does not call execute on the same executor.
  • Judge threads are not interrupted while waiting for a key.
Loading...

Input

Thread 1: executor.execute(1, taskA)
Thread 2: executor.execute(1, taskB)

Output

taskA and taskB never execute at the same time

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.