lambda会导致比赛状态吗

lambda会导致比赛状态吗

本文介绍了forEach lambda会导致比赛状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定lambda在实践中如何工作,我担心,因为在某些情况下,如果使用不正确,lambda可能会导致诸如ConcurrentModificationExceptions之类的错误,这似乎表明存在竞争状况.
考虑下面的代码.

I am unsure of how lambdas work in practice, and I am concerned since under certain circumstances, lambdas can result in errors such as ConcurrentModificationExceptions if you use them incorrectly, which seems to be indicative of a race condition.
Consider the code below.

private class deltaCalculator{
    Double valueA;
    Double valueB;

    //Init delta
    volatile Double valueDelta = null;

    private void calculateMinimum(List<T> dataSource){
        dataSource.forEach((entry -> {
            valueA = entry.getA();
            valueB = entry.getB();
            Double dummyDelta;

            dummyDelta = Math.abs(valueA - valueB);

            if(valueDelta == null){
                setDelta(dummyDelta);
            }else {
                setDelta((valueDelta > dummyDelta) ? dummyDelta : valueDelta);
            }
        }));
    }

    private void setDelta(Double d){
        this.valueDelta = d;
    }
}

forEach循环如何运行?是否将不同的调用传递到JVM认为合适的不同线程,从而打开了可能导致错误的最小计算的竞争条件的可能性?
如果没有,为什么forEach lambda会引发ConcurrentModificationException?

How does the forEach loop operate? Do different calls get passed to different threads where the JVM considers it appropriate, opening up the possibility of a race condition that could lead to incorrect minimum calculation?
If not, why can a forEach lambda throw a ConcurrentModificationException?

推荐答案

如果在运行for每个循环时尝试修改要迭代的集合,则会收到ConcurrentModificationException.可以完全在一个单独的线程中完成此操作,但是当您尝试在循环主体中修改集合时,更常见的情况会发生.

You'll get a ConcurrentModificationException if you try to modify the collection that you're iterating over while the for each loop runs. This could be done in a separate thread entirely, but much more commonly occurs when you try to modify the collection in the loop body.

不.上面的示例中没有发生多线程处理.

No. No multithreading is taking place in your example above.

这篇关于forEach lambda会导致比赛状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:23