UpdatingabooleanvalueinmultithreadedprocessinJava

I have the following code:

public class CheckIfSame implements Runnable {

private int[][] m;
private int[][] mNew;
private int row;
private boolean same;

public CheckIfSame(int[][] m,int[][] mNew,,int row,boolean same) {
    this.m = m;
    this.mNew = mNew;
    this.row = row;
    this.same = same;
}

@Override
public void run() {
    for (int i = 0; i < mUpd[0].length; i++) {
        if(m[row][i] != mUpd[row][i]) {
            same = false;
        }       
    }

}

}

Basically, the idea of this is that i use multi threading to check row by row, whether the 2 matrices differ by at least 1 element.

I activate these threads through my main class, passing rows to an executor pool.

However, for some reason, the boolean same does not seem to update to false, even if the if condition is satisfied.

回答

Multiple threads are trying to access that boolean at the same time: a race condition while updating the same variable.

Another possible scenario for non-volatile booleans in multithreaded applications is being affected by compiler optimizations - some threads may never notice the changes on the boolean, as the compiler should assume the value didn't change. As a result, until an specific trigger, such as a thread state change, threads may be reading stale/cached data.

你可以选择一个AtomicBoolean. 当您有多个线程访问布尔变量时使用它。这将保证:

  • 同步。
  • 更新的可见性(AtomicBoolean 在内部使用 volatile int)。

例如:

public class CheckIfSame implements Runnable 
{
   //...
   private AtomicBoolean same;

   public CheckIfSame(..., AtomicBoolean same) 
   {
    //...
    this.same = same;
   }

    @Override
    public void run() 
    {
      for (int i = 0; i < mUpd[0].length; i++) 
         if(m[row][i] != mUpd[row][i]) 
             same.set(false);   //  <--race conditions hate this
    }  
 }


以上是UpdatingabooleanvalueinmultithreadedprocessinJava的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>