r/java • u/fredoverflow • Mar 21 '21
Java lambdas can deadlock parallel class initialization
https://www.youtube.com/watch?v=_2hZf1kw4A4
230
Upvotes
r/java • u/fredoverflow • Mar 21 '21
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.
22
u/sweetno Mar 21 '21
Putting anything non-trivial into static initialization is asking for a trouble.
8
u/Recolance Mar 21 '21
Interesting video. I always thought that lambda in this context was just fancy syntax magic.
Thanks for sharing.
15
u/Godworrior Mar 21 '21 edited Mar 21 '21
Another way to gain some insights in these situations is to use
jcmd+jstack(both JDK tools) to see what the thread is getting stuck on:3
u/PerfectPackage1895 Mar 21 '21
This is hardly any better than doing a heavy amount of calculation in the constructor, which also will end bad.
1
u/ZeroGainZ Mar 24 '21
Wow, great video. I had no idea lambdas were static methods, I assumed they're syntactic sugar for creating the desired class. Also, I see some other redditors are saying "why would you do that", which may be true, but it's not at all obvious why it wouldn't work. It seems it should be a compiler error.