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.

1

u/DuncanIdahos9thGhola Mar 21 '21

The issue is that when you use the old way of Thread and Runnable you get a inner class. The lambda makes a static inner class. Different byte code - so to the lesson I guess is don't assume these are equivalent - even though IDEs usually give you that option to convert from one form to the other.

6

u/[deleted] Mar 21 '21

I think the lesson is to not do something weird with a class initialiser like that. Basically this is saying please refer to me before I’m in initialised.

An inner class would be illegal since it’s a static context.

It’s an interesting result, but that’s about it.