1

My application will, during runtime, contain multiple threads (in this example 7) doing independent work. However, every once in a while, the threads will have to synchronize their data.

This will be done by the threads calling the DataSynchronizer object which they all have a reference to.

My idea for flow in this class looks like this:

public class DataSynchronizer {

    public void synchronizeData(List<Data> threadData) {
        // Wait for all 7 threads to call this method

        // When all 7 are here, hold them here & do work using one of the threads
        // or a new anonymous thread

        // Release the threads & let them continue their independent work
    }
}

My question is, what is the best way for me to 'wait for all x threads' before doing the synch work?

I know that all threads will call the synchronizeData method within 1, max 2 seconds of each other.

So do I,

1) Wait for 2s after the first thread call the method and assume all threads have now also arrived? or

2) Keep a count to make sure all active threads have arrived? (App will wait for eternity if a thread crashes just before calling method)

3) Count + timeout?

4) ???

Darajan
  • 868
  • 1
  • 9
  • 23
  • 1
    You could use a [CountDownLatch](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html) with value of 7.. – TheLostMind Nov 03 '14 at 10:19
  • possible duplicate of [When setting a form's opacity should I use a decimal or double?](http://stackoverflow.com/questions/4/when-setting-a-forms-opacity-should-i-use-a-decimal-or-double) – Unihedron Nov 03 '14 at 16:43

3 Answers3

2

This is what a CyclicBarrier is for. It allows you to define spots where threads will wait until all arrive, and then optionally run a Runnable to perform synchronization or other such thing.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
2

I think you need a java.util.concurrent.CyclicBarrier.

lalsam
  • 31
  • 1
  • 2
1
  1. Assume and threads is a very risky approach.
  2. How bad is waiting for an eternity? Sounds inconvenient to me.
  3. If you hit the timeout can you do something useful? Crash the program, restart the errant thread, assume something about what it is doing?

Follow-on questions:

  • What happens if a thread doesn't participate in the synchronisation?
  • What happens if the sync is late?
  • Should your method tell one thread from another, or are they just 7 interchangeable workers?
Dan
  • 358
  • 1
  • 11