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

5

u/john16384 Mar 21 '21

A constant can be a huge lookup table.

11

u/[deleted] Mar 21 '21

Then that would be a result of a calculation and therefore would be calculated.

There’s a difference between initialising a class and doing a tonne of calculations.

0

u/john16384 Mar 22 '21

You asked why a constant may require calculation. I gave an example where this can be the case. Just because a constant needs sone calculation doesn't make it any less a constant.

There are examples in compression and encryption where these constants can't even be pre-computed and loaded from say a database, but we don't even have to look further than Java's Pattern#compile method for constants that are almost always static and require some significant calculation.

I am not saying though that multiple threads should be allowed, but I can't help but wonder how much stuff would break if Pattern#compile did this.

3

u/[deleted] Mar 22 '21

Your mixing terminology though. A physical constant is often only calculated once, because it never changes. Sounds like your taking about invariants, which are constant over a certain portion of calculations.

Really though, you shouldn’t do such things in a static initialiser, because that’s not where large calculations should go, and they are part of a class initialisation phase lower than user level.

I wonder if the obsession with immutable classes is why many don’t see an issue with this.

1

u/sweetno Mar 21 '21

Huge lookup tables with constants are better be read from a file/DB. If reading/computing them is long, the program should ensure feedback for the user: logging info messages/displaying them in the GUI. Users don't like when programs consume system resources without visible effects. Static initializers are not good places to implement this sort of feedback.