AlgoMaster Logo
AlgoMasterDesign a Timed Lockmedium

Design a Timed Lock

medium

Design a reusable lock that lets callers give up if they cannot enter within a time limit.

Implement the TimedLock class:

  • TimedLock() creates an unlocked instance.
  • tryRun(task, timeoutMillis) tries to acquire the lock within timeoutMillis milliseconds.
  • If the lock is acquired, execute task, release the lock, and return true.
  • If the timeout expires first, do not execute task and return false.

Callbacks passed to the same TimedLock must never overlap. A timeout of 0 means that the method must try immediately without waiting.

The lock must be released if the callback throws an unchecked exception or panics. The original failure should continue to the caller after cleanup. Different TimedLock instances must be independent.

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

Example 1:

Input:

Output:

Explanation: The lock is available, so the callback runs exactly once.

Example 2:

Input:

Output:

Explanation: The timeout expires while thread A still owns the lock, so taskB is not called.

Constraints

  • 0 <= timeoutMillis <= 5000
  • At most 50000 calls are made per TimedLock.
  • A task may complete normally or fail with an unchecked exception or panic.
  • Tasks do not call tryRun recursively on the same lock.
  • Judge threads are not interrupted while waiting for the lock.
  • Timing checks allow normal scheduler variance; implementations should use blocking timed-lock primitives rather than busy waiting.
Loading...

Input

lock = TimedLock()
lock.tryRun(task, 1000)

Output

true

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.