Home > Enterprise >  Sonarlint sentinel value fake positive
Sonarlint sentinel value fake positive

Time:12-22

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

CodePudding user response:

The change made by sentinel = true; is never seen by while (!sentinel). That's because of the break statement.

With that said, your code is much simpler with a for loop. Your while simply makes it complex.

for(int counter = 0; counter < array.length; counter  ) {
    out.println("Counter: "   counter);
    out.println("Array index: "   array[counter]);
    if (counter == array.length - 1) {
        out.println("End of the array reached");
        out.println("Breaking...");
    }
}

Or, even better, do the counter == array.length - 1 actions after the loop

for(int counter = 0; counter < array.length; counter  ) {
    out.println("Counter: "   counter);
    out.println("Array index: "   array[counter]);
}
out.println("End of the array reached");
out.println("Breaking...");

CodePudding user response:

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

  • Related