Sonarlint 哨兵值假阳性

Sonarlint sentinel value fake positive

我有下一个代码片段,其中 sonarlint 工具说我的布尔变量 sentinel 的计算结果总是为 true,sentinel = true 这是一个无用的 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;
            }
        }
    }
}

sonarlint 分析可能有什么问题?代码完美编译并按预期运行。

此致。

更新:

@kkk 提供了两个有价值的答案。见下文,但我把我更喜欢的放在这里:

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

使哨兵静态或用户 AtomicBoolean,这是可见性问题

sentinel = true; 所做的更改从未被 while (!sentinel) 看到。那是因为 break 语句。

话虽如此,您的代码使用 for 循环要简单得多。你的 while 只会让它变得复杂。

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...");
    }
}

或者,更好的是,在循环后执行 counter == array.length - 1 操作

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...");