Search code examples
javawhile-loopbooleansonarlintsonarlint-intellij

Sonarlint sentinel value fake positive


I have the next code snippet, where the sonarlint tool says that my boolean variable sentinel always evaluates to true, and the sentinel = true it's an useless asingment.

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        boolean sentinel = false;
        int counter = 0;
        while (!sentinel) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "End of the array reached" );
                sentinel = true;
                out.println( "Breaking..." );
                break;
            }
        }
    }
}

What could be the issue with the sonarlint analisys? Code compiles perfectly and runs as intended.

Regards.

Update:

@kkk have provided two valuable answers. See below, but I let here the one that i liked more:

import java.util.concurrent.atomic.AtomicBoolean;

import static java.lang.System.*;

public class Sentinel {

    private static final int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static void main(String[] args) {
        AtomicBoolean sentinel = new AtomicBoolean(false);
        int counter = 0;
        while ( !sentinel.get() ) {
            out.println( "Counter: " + counter);
            out.println( "Array index: " + array[counter] );
            counter++;
            if ( counter == array.length - 1 ) {
                out.println( "Counter limit reached" );
                sentinel.set( true );
                out.println( "Breaking..." );
                break;
            }
        }
    }
}

Solution

  • make sentinel static or user AtomicBoolean,it's visibility problem