Even if you need to compute them once don’t do it in an initialiser like that. This is why streams can be bad, a simple line initialisation is actually a bigger computation; and just because you can write it on a line doesn’t mean you should.
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.
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.
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.
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.