I came across the following issue when using parallel lambdas.
I have a static initialisation block in a class which iterates over an array in parallel however, i noticed from the stack trace that the very first iteration completes correctly and computers, however all subsequent iterations block. (Thread dump states "Waiting for: ") which is really not helpful.
Here is the code that thread locks.
public static class Test {
private static final Object[] objects;
static {
objects = new Object[9];
IntStream.range(0, objects.length).parallel().forEach(i -> objects[i] = null);
}
}
After some head scratching as to why setting an array index to null would cause a thread lock I came up with the following. I created a temporary array within the static block and then assigned the class array at the end which fixed the issue.
public static class Test {
private static final Object[] objects;
static {
Object[] tempObjects = new Object[9];
IntStream.range(0, tempObjects.length).parallel().forEach(i -> tempObjects[i] = null);
objects = tempObjects;
}
}
Does anyone have any insight as to why the first code block thread locks and the second code block does not?