AlgoMaster Logo
AlgoMasterDesign a One-Shot Promisemedium

Design a One-Shot Promise

medium

Design a thread-safe one-shot promise that transfers one integer value from a producer to any number of consumers.

Implement the Promise class:

  • Promise() creates an incomplete promise.
  • complete(value) atomically completes the promise with value and returns true. Only the first call may succeed. Later calls return false and must not replace the stored value.
  • get() waits until the promise is complete, then returns its value. Any number of threads may call get, and every call must return the same value.
  • isDone() returns whether the promise has completed without waiting.

Calls to all three methods may be concurrent. Completing the promise must wake every thread currently blocked in get. Writes performed by the successful producer before complete must also be visible to consumers after get returns.

This exercise combines the producer-facing promise and consumer-facing future in one class to keep the API focused on synchronization.

The judge creates all producer and consumer threads. Your implementation should provide only the synchronization inside Promise. The judge also preloads the standard concurrency and thread APIs for every supported language. You do not need to add import, include, or using statements.

Example 1:

Input:

Output:

Explanation: The first completion stores 42. The second completion is rejected and cannot overwrite it.

Example 2:

Input:

Output:

Explanation: All three consumers wait for the same completion and are released together.

Constraints

  • -1_000_000_000 <= value <= 1_000_000_000
  • At most 100 threads access one promise.
  • At most 2,000 total method calls are made on one promise.
  • complete, get, and isDone may be called concurrently.
  • Every promise on which the judge calls get is eventually completed.
  • Judge threads are not interrupted while blocked in get.
Loading...

Input

promise = Promise()
promise.isDone()
promise.complete(42)
promise.get()
promise.complete(99)
promise.get()

Output

[false, true, 42, false, 42]

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.