Question

I have a simple java application which calculates prime numbers up to a certain user-given number and prints out the numbers. I've built upon this to include four separate threads which iterate through 4 separate ranges of numbers. Once all 4 threads have completed their iterations I want to print the final ArrayList.

I'm currently getting a ConcurrentModificationException because after I start the 4 threads, the next line of code is the print statement which is trying to print the ArrayList which is at that moment being modified by at least one of the still active threads.

Therefore, I want to be able to have the print statement execute after all 4 threads have died. Furthermore, I would like to do this without using a spinning loop. I have nothing in particular against using a spinning loop except that I imagine there is a better way to do this and I would probably have to assign greater priorities to the 4 threads in order to prevent the spinning loop from using up a significant amount of the CPU.

Was it helpful?

Solution 2

Use a CountdownLatch. The Javadoc for that class tells how to have

  1. The main thread creates the latch with the number of threads.
  2. The main thread starts all the working threads.
    1. Each thread has a reference to the latch.
    2. It counts the latch down when it finishes its work.
  3. The main thread waits for the latch to count down to 0.
  4. The main thread does the printing job.

OTHER TIPS

Use a CountDownLatch initialized to 4; the print thread awaits the latch, and the worker threads call countdown on the latch before they terminate.

Be sure to properly synchronize your ArrayList as well if four threads are modifying it at once; you may want to use a ConcurrentLinkedQueue instead (or else use a different ArrayList for each thread)

If you use a java.util.concurrent.BlockingQueue, each thread could put() an item on the blocking queue when it is finished.

Before the print statement, the code could do a take() from the blocking queue and only proceed when the take() has returned once for each thread. The printing thread will block on the take() while there is nothing there for it to take. That will guarantee that the printing doesn't commence until all the threads have finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top