Random wrong result from bitwise and operation in Java

Viewed 99

Following test fails for random i:

    @Test
    public void test() {
        for (int i = 0; i < 1_000_000; i++) {
            boolean isTrue = and128(new byte[] {-1});

            if (!isTrue) {
                fail("broken: " + i + " " + isTrue);
                break;
            }
            clearCache();
        }
    }

    private void clearCache() {
        for (int i = 0; i < 100; i++) {
            and128(new byte[] {(byte) i});
        }
    }

    public static boolean and128(byte[] byteData) {
        return ((byteData[0] & 128) > 0);
    }

Because of randomness, I would blame Java Runtime. If I inline the method and128, I cannot reproduce the problem. Also if I just pass one byte instead of byte array, test passes. I am using OpenJDK 14.0.2. Issue seems to be fixed in 15.0.2. It still seems to be present in 15.0.1 and I cannot find a bug that would correspond to this.

EDIT: I added this "clearCache" method that just runs on the side and makes bug easier to reproduce. I guess it prevents some java optimization.

0 Answers
Related