r/java • • Mar 21 '21

Java lambdas can deadlock parallel class initialization

https://www.youtube.com/watch?v=_2hZf1kw4A4
230 Upvotes

46 comments sorted by

View all comments

84

u/fredoverflow Mar 21 '21

TL;DW Lambda bodies are implemented as private static methods, but during class initialization, other threads are blocked from calling static methods.

38

u/[deleted] Mar 21 '21

Whilst interesting; who would do such a thing? Having a heavy static class initialiser using a parallel stream like that.. ouch.

35

u/AndrewHaley13 Mar 21 '21

Well, this kind of edge case really needs to be fixed. It's far from obvious that lambda streams shouldn't be used in static initializers.

7

u/[deleted] Mar 21 '21

It’s obvious that you don’t put any kind of heavy computation into a static initialiser. Anything that uses parallel stream would be by definition heavy.

What would be your proposed fix?

23

u/[deleted] Mar 21 '21

You can't judge how heavy a computation is by looking at the code in your static initializer. You might just do "new Foo()" and THAT inside uses parallel streams for some reason.

If they wanted to restrict calling arbitrary code... they should've restricted calling arbitrary code.

2

u/Muoniurn Mar 22 '21

I didn’t test it, but I believe that there is no problem with calling another class that creates threads. The problem here is about calling the same class’s static methods from another thread from the static initializer. Which you can’t do by a trivial new Foo(), only by this already red flag raising line in the video. (You can fall into this trap by new Foo() that awaits a lambda though, I believe . But I would yet again question that code)

Nonetheless, a compiler warning would be appreciated if it can prove in this specific case that a deadlock can arise.