1

I have a strange deadlock that only seems to happen outside of main().

    static
    {
        init();
    }

    private static final void init()
    {
        ForkJoinPool forkJoinPool = null;
        try
        {
            forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
/*A*/       List<Void> list = new ArrayList<>();
            for (int i = 0; i < 100; i++) list.add(null);
            Object obj = forkJoinPool.submit(() ->
            {
                list.stream().parallel().forEach(t ->
                {
/*B*/               System.err.println(1);
                });
                return null;
            }).get();
            System.out.println("no deadlock: " + obj);
        }
        catch (InterruptedException | ExecutionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (forkJoinPool != null)
            {
                forkJoinPool.shutdown();
            }
        }
    }

The code above has two outcomes.

  1. If I set a break-point at /*A*/ and then resume execution then it will print between one and approx ten 1's.
  2. If I set a break-point at /*A*/ and then step over the execution of the stream it will print only one 1.
  3. If i set a break-point at /*B*/ only one thread will hit the break-point and when resumed (the entire program) will only print one 1. In all cases "no deadlock" is not printed.

My first thought was that a synchronised block within the function i was calling was thread-locking, however, with the test code above, that is ruled out.

My second thought was that somewhere else was executing something that is using the global forkjoinpool. This isn't the case, but just in case i ran the code within a custom forkjoinpool, this results in nothing getting printed, and any breakpoints within the forkjoinpool (before execution of the list#parallelstream) are not hit.

My final guess is that it is caused by running inside a method called via the static{} block. If this code being ran in the static{} block is the cause, why is this so?

John Kugelman
  • 307,513
  • 65
  • 473
  • 519
jordan t
  • 126
  • 9
  • 4
    See also: [Why using parallel streams in static initializer leads to not stable deadlock](https://stackoverflow.com/questions/53724687/why-using-parallel-streams-in-static-initializer-leads-to-not-stable-deadlock). – John Kugelman Nov 10 '19 at 15:19

0 Answers0