Pergunta

I am reading the book Java Concurrency in Practice where it says,

CyclicBarrier allows a fixed number of parties to rendezvous repeatedly at a barrier point and is useful in parallel iterative algorithms that break down a problem into a fixed number of independent subproblems.

Can someone give an example of how it breaks down a problem into multiple independent subproblems?

Foi útil?

Solução

You have to break the problem down into multiple independent subproblems yourself.

Barriers ensure that each party completes the first subproblem before any of them start on the second subproblem. This ensures that all of the data from the first subproblem is available before the second subproblem is started.

A CyclicBarrier specifically is used when the same barrier is needed again and again when each step is effectively identical. For example, this could occur when doing any sort of multithreaded reality simulation which is done in steps. The CyclicBarrier would ensure that each thread has completed a given step before all threads will begin the next step.

Outras dicas

There is yet another important difference between CountDownLatch and CyclicBarrier and that is: the thread synchronized on CountDownLatch cannot indicate the other threads that something has gone wrong with it, so that the other threads may have a choice to either continue your abort the entire cooperative operation.

In case of a CycliBarrier while one of the threads is waiting on await() some other thread is interrupted or is timed-out, then a BrokenBarrierException will occur on current thread indicating something has gone wrong in one of the cooperating threads.

BrokenBarrierException will also occur in other circumstances which you can find in Javadoc on await() method.

Out-of-the-box, CountDownLatch does not offer this feature.

IF you have an algorithm that can be broken down in independent subproblems,
THEN a CyclicBarrier is useful for all your threads to meet at the end of their calculation and, for example, merge their results.

Note that the Fork/Join framework introduced in Java 7 enables you to do the something similar without needing to use a CyclicBarrier.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top