corretto / corretto-17

Amazon Corretto 17 is a no-cost, multi-platform, production-ready distribution of OpenJDK 17
GNU General Public License v2.0
214 stars 50 forks source link

Random failure when using `parallel()` method on java.util.Arrays streams. #186

Closed kumaran-sowrirajan closed 5 months ago

kumaran-sowrirajan commented 5 months ago

Describe the bug

Random failure when using parallel() method on java.util.Arrays streams.

To Reproduce

Use the test code (pasted below) and execute them repeatedly via any IDE and you will see an assertion failure. It worked if I do not include the parallel option.


    @Test
    public void testParallel() {
        List<String> instances = new ArrayList<>();
        int[] numbers = new int[10];
        Arrays.fill(numbers, 2);
        Arrays.stream(numbers).parallel().forEach(value -> {
            instances.add(String.valueOf(value + 1));
        });
        Assertions.assertEquals(numbers.length, instances.size());
    }
`

### Expected behavior
No failures to be reported when running the above tests.

### Platform information
    OS: Windows
    Version: **Corretto 17.0.10**
benty-amzn commented 5 months ago

ArrayList::add is not specified to be thread safe.

Please see the documentation for ArrayList, specifically this section:

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method.