O uso de um semáforo dentro de uma ação de fluxo paralelo Java 8 aninhada pode DEADLOCK. Isso é um inseto?

Considere a seguinte situação: Estamos usando um fluxo paralelo do Java 8 para executar um loop forEach paralelo, por exemplo,

IntStream.range(0,20).parallel().forEach(i -> { /* work done here */})

O número de encadeamentos paralelos é controlado pela propriedade do sistema "java.util.concurrent.ForkJoinPool.common.parallelism" e geralmente igual ao número de processadores.

Agora, suponha que gostamos de limitar o número de execuções paralelas para um trabalho específico - por exemplo, porque essa parte consome muita memória e a restrição de memória implica um limite de execuções paralelas.

Uma maneira óbvia e elegante de limitar execuções paralelas é usar um semáforo (sugeridoaqui), por exemplo, a seguinte parte do código limita o número de execuções paralelas a 5:

        final Semaphore concurrentExecutions = new Semaphore(5);
        IntStream.range(0,20).parallel().forEach(i -> {

            concurrentExecutions.acquireUninterruptibly();

            try {
                /* WORK DONE HERE */
            }
            finally {
                concurrentExecutions.release();
            }
        });

Isso funciona muito bem!

No entanto: usando qualquer outro fluxo paralelo dentro do trabalhador (em/* WORK DONE HERE */) pode resultar emimpasse.

Para mim, este é um comportamento inesperado.

Explicação: Como os fluxos Java usam um conjunto ForkJoin, o forEach interno está bifurcando e a associação parece estar esperando para sempre. No entanto, esse comportamento ainda é inesperado. Observe que fluxos paralelos funcionam mesmo se você definir"java.util.concurrent.ForkJoinPool.common.parallelism" para 1.

Observe também que ele pode não ser transparente se houver um paralelo interno para cada um.

Pergunta, questão: Esse comportamento está de acordo com a especificação do Java 8 (nesse caso, implicaria que o uso de semáforos dentro de trabalhadores de fluxos paralelos é proibido) ou isso é um bug?

Por conveniência: Abaixo está um caso de teste completo. Quaisquer combinações dos dois booleanos funcionam, exceto "true, true", o que resulta em um impasse.

Esclarecimento: Para esclarecer a questão, deixe-me enfatizar um aspecto: o impasse não ocorre noacquire do semáforo. Observe que o código consiste em

adquirir semáforoexecutar algum códigosemáforo de liberação

e o impasse ocorre em 2. se esse trecho de código estiver usando OUTRO fluxo paralelo. Em seguida, o impasse ocorre dentro desse OUTRO fluxo. Como conseqüência, parece que não é permitido usar fluxos paralelos aninhados e operações de bloqueio (como um semáforo) juntos!

Observe que está documentado que os fluxos paralelos usam um ForkJoinPool e que ForkJoinPool e Semaphore pertencem ao mesmo pacote -java.util.concurrent (portanto, seria de esperar que eles interoperassem bem).

/*
 * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected].
 *
 * Created on 03.05.2014
 */
package net.finmath.experiments.concurrency;

import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * This is a test of Java 8 parallel streams.
 * 
 * The idea behind this code is that the Semaphore concurrentExecutions
 * should limit the parallel executions of the outer forEach (which is an
 * <code>IntStream.range(0,numberOfTasks).parallel().forEach</code> (for example:
 * the parallel executions of the outer forEach should be limited due to a
 * memory constrain).
 * 
 * Inside the execution block of the outer forEach we use another parallel stream
 * to create an inner forEach. The number of concurrent
 * executions of the inner forEach is not limited by us (it is however limited by a
 * system property "java.util.concurrent.ForkJoinPool.common.parallelism").
 * 
 * Problem: If the semaphore is used AND the inner forEach is active, then
 * the execution will be DEADLOCKED.
 * 
 * Note: A practical application is the implementation of the parallel
 * LevenbergMarquardt optimizer in
 * {@link http://finmath.net/java/finmath-lib/apidocs/net/finmath/optimizer/LevenbergMarquardt.html}
 * In one application the number of tasks in the outer and inner loop is very large (>1000)
 * and due to memory limitation the outer loop should be limited to a small (5) number
 * of concurrent executions.
 * 
 * @author Christian Fries
 */
public class ForkJoinPoolTest {

    public static void main(String[] args) {

        // Any combination of the booleans works, except (true,true)
        final boolean isUseSemaphore    = true;
        final boolean isUseInnerStream  = true;

        final int       numberOfTasksInOuterLoop = 20;              // In real applications this can be a large number (e.g. > 1000).
        final int       numberOfTasksInInnerLoop = 100;             // In real applications this can be a large number (e.g. > 1000).
        final int       concurrentExecusionsLimitInOuterLoop = 5;
        final int       concurrentExecutionsLimitForStreams = 10;

        final Semaphore concurrentExecutions = new Semaphore(concurrentExecusionsLimitInOuterLoop);

        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism",Integer.toString(concurrentExecutionsLimitForStreams));
        System.out.println("java.util.concurrent.ForkJoinPool.common.parallelism = " + System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism"));

        IntStream.range(0,numberOfTasksInOuterLoop).parallel().forEach(i -> {

            if(isUseSemaphore) {
                concurrentExecutions.acquireUninterruptibly();
            }

            try {
                System.out.println(i + "\t" + concurrentExecutions.availablePermits() + "\t" + Thread.currentThread());

                if(isUseInnerStream) {
                    runCodeWhichUsesParallelStream(numberOfTasksInInnerLoop);
                }
                else {
                    try {
                        Thread.sleep(10*numberOfTasksInInnerLoop);
                    } catch (Exception e) {
                    }
                }
            }
            finally {
                if(isUseSemaphore) {
                    concurrentExecutions.release();
                }
            }
        });

        System.out.println("D O N E");
    }

    /**
     * Runs code in a parallel forEach using streams.
     * 
     * @param numberOfTasksInInnerLoop Number of tasks to execute.
     */
    private static void runCodeWhichUsesParallelStream(int numberOfTasksInInnerLoop) {
        IntStream.range(0,numberOfTasksInInnerLoop).parallel().forEach(j -> {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
            }
        });
    }
}

questionAnswers(3)

yourAnswerToTheQuestion