Avoiding possible concurrency issue when returning a LIST

Here is the sequence that prevents me from asking for the standard remedy for the concurrency problem

  • Create list object (lst)
  • Initiate multi-threaded streams (update streams)
  • Send this lst to each update stream to update (add) it.
  • Wait a while (t1) for the update streams to update.
  • After the time t1 has expired, return lst to another application (Consumer-App) that is not under our control.
  • When returning it, Updater Threads may still update the lst.
  • The Consumer-App does not know if the list is being updated in the background using update streams.
  • The consumer-application performs a list of operations (add / remove) on lst.

Problem: This will lead to a concurrency issue.

How to solve this?

How to stop updating threads after t1 efficiently? Or is there a standard way to handle this? Will there be any help synchronizedList (Collections.synchronizedList(new ArrayList()))

with this?

Edit: I am also aware of the CopyOnWriteArrayList. But I am focused on a simple ArrayList on this

+1


source to share


2 answers


You can use a service executor to create and terminate streams, and a CopyOnWriteArrayList instance, address concurrency.

 private CopyOnWriteArrayList<someObject> someArrayList = new CopyOnWriteArrayList<someObject>();

      

...



 class NodeStatusThread implements Runnable {

        private ExecutorService UpdaterThreadExecutor = null;
        private int numThrd = 20; //threads 
        private int timeout = 10; // ten-seconds 

        @Override
        public void run() {
            for (int i=0;i<numThrd; i++ ) {
                UpdaterThreadExecutor.execute(new UpdaterThread());
            }
            UpdaterThreadExecutor.shutdown();


            try{
                //Wait for thread completion
                if(!UpdaterThreadExecutor.awaitTermination(timeout, TimeUnit.SECONDS)){  //return false is timeout is surpassed
                    UpdaterThreadExecutor.shutdownNow(); //forces thread termination
                }
            }catch(InterruptedException e){
                UpdaterThreadExecutor.shutdownNow();
            }

        }

}

      

...



 class UpdaterThread implements Runnable { 

    @Override
    public void run() {
        omeArrayList.add(someObject);

        someArrayList.remove(someObject);
    }
 }

      

+1


source


4 - Wait a while (t1) for the update streams to be updated.

Your design is wrong here. You can never be sure that each thread has completed updating the list.



You must use a synchronization mechanism so that your consumer thread can wait for each producer to complete.

Use CountDownLatch or CyclicBarrier .

0


source







All Articles