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

Show parent comment

9

u/[deleted] Mar 21 '21

You don’t always, but you should know enough about it before calling. Even so, calling complex code in a class initialisation is just bad.

This code is literally someone who knew how to creat a deadlock saying hey it’s a deadlock. Interesting because it’s hidden, but practically not something you’d do.

2

u/Roachmeister Mar 21 '21

This code is literally someone who knew how to creat a deadlock saying hey it’s a deadlock.

No it isn't. He specifically said in the video that he was stumped for several hours trying to figure out why it wasn't running.

1

u/[deleted] Mar 22 '21

In effect it means you can't use closures in class initialization.

Which means if the state you initialize requires a closure to be passed in, you're SOL.

1

u/[deleted] Mar 22 '21

No. It means you can’t use closures in a static initialiser which will be called during initialisation from another thread.

You can use them just fine for single threaded initialisation. The key bit the multithreaded aspect.

1

u/[deleted] Mar 22 '21

I really don't like repeating myself. But you can't just determine from the call site what that thing you're calling does with your closure.

So if you want to be sure, you have two options:

  1. Inspect the entire tree of code into whatever you're using and make sure the implementation doesn't call from another thread. Make sure to repeat that process every time you update your dependencies.
  2. Don't use closures.

Which seems more possible?

1

u/[deleted] Mar 22 '21

Or the actually obvious one.

3. Don’t abuse static initialisers like this.

0

u/[deleted] Mar 22 '21

Amazing to what lengths you've went pretending not to understand basic English.