Building H2O
MediumConcurrencySemaphoreBarrierThread CoordinationCyclicBarrier
Problem Statement
There are two kinds of threads: hydrogen (H) and oxygen (O). Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule — exactly 2 hydrogen and 1 oxygen — can be formed. Threads pass the barrier by invoking releaseHydrogen() or releaseOxygen().
You must guarantee that all threads from one molecule bond before any threads from the next molecule do. (Threads do not need to be paired explicitly; just guarantee the composition 2H + 1O passes the barrier together.)
class H2O {
public H2O() {}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
// releaseHydrogen.run() signals that this thread can be released
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
// releaseOxygen.run() signals that this thread can be released
}
}
Key Entities
- H2O: Central coordinator maintaining counts of waiting H and O threads.
- Semaphore for H: Allows exactly 2 hydrogen threads per molecule.
- Semaphore for O: Allows exactly 1 oxygen thread per molecule.
- CyclicBarrier(3): Ensures all three threads of one molecule clear together before the next molecule starts.
Requirements
- Every water molecule must consist of exactly 2 H and 1 O.
- No thread from the next molecule passes the barrier until the current molecule is complete.
- The input string is guaranteed to form complete molecules (e.g.,
"OOHHHH"= 2 molecules). - Solution must be deadlock-free.
Asked at: LinkedIn, Google, Amazon, Microsoft, Uber
!Constraints
- Input string length is divisible by 3.
- Number of 'H' characters is twice the number of 'O' characters.
- Total input length ≤ 300 characters.
- Each thread calls its method exactly once.
Output
Run or submit your code to see output here.