如何避免并发访问资源?

How to avoid concurrent access to a resource?

我有四个线程 运行 异步使用 CompletableFuture,如下面的代码所示。他们都应该访问 "grownSeedXYList"。有时当我 运行 我收到的代码没有错误,但有时我收到 "java.util.concurrent.completionexception" 我认为这是因为 "grownSeedXYList" 未同步。

请告诉我如何同步"grownSeedXYList"?

更新:

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

四个线程运行使用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]);
    }
}

在Java中,对资源使用互斥锁。

可以在此处找到带有转向标志的更安全的锁。 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();
        }
    }
}

您的 grownSeedXYList 已在线程之间共享。您最简单的选择是使用如下声明:

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

这将使 grownSeedXYList 集合成为线程安全的。仅供参考,我相信,在没有 CompletionException 的完整回溯的情况下,您可能在调用 join 时收到了它,因为其中一个线程捕获了 ConcurrentModificationException

编辑:正如@user270349 在下面的评论中指出的那样以及 javadoc 指出的那样,如果您对其进行迭代,您仍然需要在 grownSeedXYList 上进行同步。在这种情况下,您可以执行以下操作:

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

但是,如果您使用 for/each 块,则不需要同步:

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