How to avoid concurrent access to a resource?

767 Views Asked by At

I have four threads runs asynchronously using CompletableFuture as shown below in the code. and all of them should access "grownSeedXYList". sometime when i run the code i receive no errors, but some time i receive "java.util.concurrent.completionexception" and i thinkk this is because the "grownSeedXYList" is not synchronized.

please let me know how to synchronize "grownSeedXYList"?

update:

this.grownSeedXYList is a list that will be populated with some Point objects based on the runnable class used (GrowSeedSERun, GrowSeedNWRun, GrowSeedNERun, GrowSeedSWRun)

the four threads run using Compltable future

this.grownSeedXYList = new ArrayList<Point>();
this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor);
                this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor);
                this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor);
                this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor);
                CompletableFuture.allOf(this.growSeedFutureList).join();

GrowSeedSERun class:

private class GrowSeedSERun implements Runnable {

    private Mat saliencyMat = null;
    private double seedVal;
    private Point seedXY = null;

    public GrowSeedSERun(Mat saliencyMat, Point seedXY, double seedVal) {
        // TODO Auto-generated constructor stub
        this.saliencyMat = saliencyMat;
        this.seedXY = seedXY;
        this.seedVal = seedVal;
    }
    public void run() {
        // TODO Auto-generated method stub
        growSeedsSE(this.saliencyMat, this.seedXY, this.seedVal);
    }
}

growSeedsSE:

private void growSeedsSE(Mat saliencyMat, Point seedXY, Double seedVal) {
    // TODO Auto-generated method stub
    int origX = (int) seedXY.x;
    int origY = (int) seedXY.y;

    if ( this.withinRange(saliencyMat.get(origY, ++origX)[0]) ) {

        if ( (this.grownSeedXYList != null) && (!this.grownSeedXYList.contains(new Point(origX, origY))) ) {

            //Log.D(TAG, "growSeedsSE", "newX: origX: "+origX);
            //Log.D(TAG, "growSeedsSE", "newX: origY: "+origY);
            //Log.D(TAG, "growSeedsSE", "newX: value: "+saliencyMat.get(origY, origX)[0]);

            this.grownSeedXYList.add(new Point(origX, origY));

        } else {
            Log.D(TAG, "growSeedsSE", "point: "+ new Point(origX, origY)+" contained in the list");
        }
        this.growSeedsSE(this.saliencyMat, new Point(origX, origY), this.saliencyMat.get(origY, origX)[0]);

    } else if ( this.withinRange(saliencyMat.get(++origY, (int) this.seedXY.x)[0]) ) {
        origX = (int) this.seedXY.x;

        if ( (this.grownSeedXYList != null) && (!this.grownSeedXYList.contains(new Point(origX, origY))) ) {

            //Log.D(TAG, "growSeedsSE", "newY: origX: "+origX);
            //Log.D(TAG, "growSeedsSE", "newY: origY: "+origY);
            //Log.D(TAG, "growSeedsSE", "newY: value: "+saliencyMat.get(origY, origX)[0]);

            this.grownSeedXYList.add(new Point(origX, origY));

        }  else {
            Log.D(TAG, "growSeedsSE", "point: "+ new Point(origX, origY)+" contained in the list");
        }
        this.growSeedsSE(this.saliencyMat, new Point(origX, origY), this.saliencyMat.get(origY, origX)[0]);
    }
}
2

There are 2 best solutions below

6
On BEST ANSWER

Your grownSeedXYList is shared among the threads. Your easiest option would be to use declare it as follows:

this.grownSeedXYList = Collections.synchronizedList(new ArrayList<Point>());

That will cause the grownSeedXYList collection to be thread safe. FYI, I believe, in the absence of the complete walkback for the CompletionException that you probably received it on the call to join because on of the threads caught a ConcurrentModificationException

Edit: As called out by @user270349 in the comments below and as noted by the javadoc, you still will need to synchronize on grownSeedXYList if you iterate over it. In such a case, you would do the following:

synchronized(grownSeedXYList) {
    Iterator i = grownSeedXYList.iterator();
    while (i.hasNext())
        foo(i.next());
    }
}

However, no synchronization is necessary if you use a for/each block as in:

for (Point point : grownSeedXYList) {
    foo(point);
}
0
On

In Java, use a Mutex lock around the resource.

A safer lock with turn flags can be found here. https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class main {

    public static void main(String[] args) 
    {
        final Lock lock = new ReentrantLock();

        try {
            lock.tryLock();
        } finally {
            lock.unlock();
        }
    }
}