I have a question about a HorseRace example from Bruce Eckel's Thinking in Java.
The question is: why do we need to synchronize strides field in the Horse class? The only two threads that have access to it are Horse itself and Runnable in CyclicBarrier. And the documentation for CyclicBarrier says:
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.
As far as I understand, this means that when the last active Horse thread calls await and goes to sleep, CyclicBarrier runs its Runnable before any Horse threads are awakened so there will be no collision when accessing strides. Am I right?
Your understanding is not right. You have quoted the CyclicBarrier API - it says "an optional Runnable command that is run once per barrier point" - what is your 'barrier point' here?
SCJP 1.4, OCMJEA/SCEA 5.0.
Joined: Aug 31, 2012
Well, the barrier point is reached when each Horse makes one stride, following which they all goes into a blocking state and CyclicBarrier performs its action and then releases threads.
BTW, I've changed the code to make some observations:
I re-read your initial post. I think you are right. I was wrong in my earlier post. I initially thought a single object is shared by all the threads (which is not the case here).
And your understanding of CyclicBarrier is correct. I am not sure why the author has synchronized access to strides here...