Quick revision
The short answer
A one-shot gate holds a boolean open field guarded by this: open() is synchronized, sets open = true and calls notifyAll(), and awaitOpen() is synchronized and loops while (!open) wait(), letting InterruptedException propagate. A CountDownLatch(1) gives the same behaviour with countDown() and await(), in less code, with timeouts built in, so in production we prefer the latch; both versions guarantee that everything done before open() is visible after awaitOpen() returns.
What to remember
In this answer, we wrote a one-shot gate with a boolean guarded by this, a synchronized open() that sets it and calls notifyAll(), and a synchronized awaitOpen() that waits in a while loop and propagates InterruptedException. We saw the broken versions that drop the loop, the lock or notifyAll, and we replaced the whole class with CountDownLatch(1), which does the same in three lines and adds timeouts. Both establish happens-before from open() to the return of awaitOpen(), so work done before opening is visible to every thread that passes.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A one-shot gate holds a boolean open field guarded by this: open() is synchronized, sets open = true and calls notifyAll(), and awaitOpen() is synchronized and loops while (!open) wait(), letting InterruptedException propagate. A CountDownLatch(1) gives the same behaviour with countDown() and await(), in less code, with timeouts built in, so in production we prefer the latch; both versions guarantee that everything done before open() is visible after awaitOpen() returns.
Why this question is asked
A gate is one of the simplest coordination tools: threads wait at it until someone opens it, and once open it stays open. We need one when services must not handle traffic before a cache is warm, when test threads must start at the same moment, or when a component must wait for configuration to arrive. Interviewers ask us to write it by hand because a dozen lines reveal whether we really understand intrinsic locks, wait and notifyAll, interruption and visibility. In this answer, we will write the gate step by step, look at the broken versions people commonly write, compare it with CountDownLatch, and finish with the visibility guarantee both give.
1What the Gate Must Do
Before writing code, it helps to state the contract precisely. The gate starts closed. Any number of threads may call awaitOpen(), and each one blocks while the gate is closed. Some thread calls open() once; at that moment every waiting thread wakes up and returns, and every later call to awaitOpen() returns immediately. Calling open() again is harmless. A waiting thread that is interrupted must stop waiting and report it by throwing InterruptedException.
An intrinsic lock is the lock built into every Java object, the one synchronized uses. We will use the gate object itself, this, as both the lock and the place where threads wait.
2Writing the Gate With Intrinsic Locks
The state is a single boolean. We document that it is guarded by this, meaning every read and write happens while holding the lock on the gate.
Notice how each line earns its place. Both methods are synchronized, so they hold the gate's lock while they touch open. awaitOpen() checks the flag in a while loop, so a spurious wakeup, a wakeup with no notification, simply leads to another wait(). wait() releases the lock while the thread sleeps, which is what allows open() to enter its synchronized block at all. And notifyAll() wakes every waiter, not just one, because all of them should pass.
We let InterruptedException propagate from awaitOpen() instead of catching it. The reason is that interruption is a request from someone else to stop waiting, and only the caller knows what stopping means. Swallowing it inside the gate would leave the thread stuck in a loop it was asked to leave. The caller in the example restores the interrupt flag, which is the polite thing to do when it cannot rethrow.
3The Broken Versions We Should Recognise
Hand-written gates fail in a few predictable ways, and reviewers should look for each of them.
The first passes the gate on a spurious wakeup. The second is a data race: the write to open is not under the lock, so a waiter may not see it, and the ordering between the check and the wait is no longer protected. The third fails loudly, which is at least easy to find. There is also a quieter mistake: using notify() instead of notifyAll(). With several waiters, only one would wake, and the others would sleep until something else happened to wake them.
4The Same Gate With CountDownLatch
CountDownLatch from java.util.concurrent is a counter that threads can wait on. await() blocks until the count reaches zero, and countDown() decrements it. A latch created with a count of 1 is exactly a one-shot gate.
| Aspect | synchronized + wait/notifyAll | CountDownLatch(1) |
|---|---|---|
| Lines of logic | About 10 | About 3 |
| Spurious wakeups | Our while loop must handle them | Handled inside the class |
| Timed wait | Deadline loop written by hand | await(timeout, unit) |
| Interruption | Propagated if we declare it | Propagated by await() |
| Reopen or reset | Possible if we add it | Not possible; use a new latch |
| Visibility guarantee | Lock release -> lock acquire | countDown() -> await() return |
The latch version has no loop, no lock and no flag to forget, and it gives us a timed wait for free. Writing a correct timed wait by hand needs a deadline, a loop that waits for the remaining time, and careful handling of early returns, which is easy to get wrong. CountDownLatch has also been tested by the JDK team on every platform Java runs on.
5Why Both Versions Make Earlier Writes Visible
A gate is only useful if the thread that passes it sees the work done before it was opened. Suppose the opener fills a cache and then opens the gate. Without a guarantee, a waiter could pass the gate and read a cache that still looks empty to it.
The Java Memory Model gives that guarantee through happens-before, the rule that says when one thread's writes must be visible to another. In the hand-written gate, the opener writes the cache, then releases the lock at the end of open(). The waiter acquires the same lock when it returns from wait() and leaves awaitOpen(). An unlock happens-before every later lock of the same monitor, so everything the opener did before open() is visible to the waiter after awaitOpen(). CountDownLatch documents the same edge: actions before countDown() happen-before actions after a successful return from await().
So both versions are correct in this respect, as long as the cache is filled before open() is called. Writes made after open() are not covered and need their own synchronization.
6Follow-up questions
Why not make the open field volatile and skip synchronized?
volatile would make the flag visible, but wait() and notifyAll() still need the monitor, and the check-then-wait step must be atomic with the notification. Without the lock, a waiter could read false, the opener could set true and notify, and only then the waiter would call wait() and sleep forever. The lock is what closes that gap.
Could we make the gate reusable, so it can close again?
We could add a close() method, but a reusable gate raises new questions, such as whether a thread woken by open() should still pass if the gate closed again before it got the lock. A generation counter usually answers that. In the library, CyclicBarrier and Phaser cover reusable coordination, and for a one-time signal a fresh CountDownLatch per cycle is simpler.
What would you use if the result of the waited-for work also matters?
A CompletableFuture. It is a one-shot gate that also carries a value or an exception: complete(value) opens it and join() or get() waits for it. If the waiters need the loaded data and must also learn about a failure, a future expresses that better than a latch plus separate fields.
7Conclusion
In this answer, we wrote a one-shot gate with a boolean guarded by this, a synchronized open() that sets it and calls notifyAll(), and a synchronized awaitOpen() that waits in a while loop and propagates InterruptedException. We saw the broken versions that drop the loop, the lock or notifyAll, and we replaced the whole class with CountDownLatch(1), which does the same in three lines and adds timeouts. Both establish happens-before from open() to the return of awaitOpen(), so work done before opening is visible to every thread that passes.
Open with
I would keep a private boolean open field and document that it is guarded by this. open is synchronized, sets open to true and calls notifyAll, so every waiting thread wakes. awaitOpen is also synchronized and does while not open, wait, and it declares InterruptedException rather than swallowing it, because interruption is the caller's request to stop waiting.
Then, if they want more
The while loop matters because of spurious wakeups, and the lock matters because the check and the wait must be atomic with respect to the notification; otherwise a waiter can miss it and sleep forever.
In terms of visibility, releasing the lock in open happens-before acquiring it in awaitOpen, so anything the opener did before opening is visible to the threads that pass.
Then I would point out that CountDownLatch with a count of one is exactly this gate: countDown opens it, await waits, it has a timed await, and the JDK documents the same happens-before edge from countDown to the return of await.
In real code I would use the latch, or a CompletableFuture if the waiters also need a result or an error. Hand-written versions are where I have seen bugs like an if instead of a while, or the flag written outside the lock, so I keep them for interviews and teaching.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement a one-shot gate class with methods open() and awaitOpen() using intrinsic...": https://scrivio-interview-library.netlify.app/java/synchronization/7922cae234/