Horse race simulation — A java threading exercise
I encountered this in a recent interview, and I think it is an interesting exercise.
The goal is to simulate a horse race with ’n’ horses. At the end of the race, we need to declare the finishing position of each horse. Neet problem statement and imaginative!
The finer details:
- All horses shall start at the same time; how do we start all the threads nearly instantly? (Of course, CPU scheduling has to be disregarded here for the spirit of the question.)
- Upon finishing, we need to record the ordinal position of each thread (horse).
Code:

https://github.com/gkns/java-dojo/blob/master/src/main/java/threading/HorseRace.java
The use of Cyclicbarrier
The cyclic barrier here is used to guarantee (as closest possible) that each horse gets a chance to start at the same time. (However, in reality, due to CPU scheduling, this will not happen practically.) Each thread calls barrier.await() → causing the thread to wait for the barrier to trip (Analogous to opening the gates). The barrier is tripped in the main thread, causing all threads to be eligible for scheduling and hopefully start parallel execution.
The AtomicInteger is used to keep track of the finish positions.
We can also use a CountDownLatch (or even a Phaser) to achieve the same, However, a barrier seems more appropriate here.
How can we use a CountDownLatch?
CountDownLatch latch = new CountDownLatch(nHorses+1);
....
Thread(() -> { try {
...
latch.await();...
}...
// Open the gates.
IntStream.range(0, nHorses+1).forEach(i-> latch.countDown());
...
And, a question!
Do you think the threads themselves finish at different times (regardless of the random sleep in each thread in the code above, the result is the same.) Or are the threads waiting for a chance to increment the AtomicInteger? What do you think is happening behind the scenes?
Cheers!