asdasdidontcare
asdasdidontcare

Reputation: 65

Updating a boolean value in multithreaded process

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.

Upvotes: 6

Views: 1170

Answers (1)

aran
aran

Reputation: 11890

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.

You could choose an AtomicBoolean. Use it when you have multiple threads accessing a boolean variable. This will guarantee:

  • Synchronization.
  • Visibility of the updates (AtomicBoolean uses a volatile int internally).

For example:

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
    }  
 }

Upvotes: 7

Related Questions