It’s obvious that you don’t put any kind of heavy computation into a static initialiser. Anything that uses parallel stream would be by definition heavy.
You can't judge how heavy a computation is by looking at the code in your static initializer. You might just do "new Foo()" and THAT inside uses parallel streams for some reason.
If they wanted to restrict calling arbitrary code... they should've restricted calling arbitrary code.
Well, when you program, you don't just slap constructor and method invocations here and there. More often than not you get a rough idea what are the runtime characteristics of the used APIs: memory usage and algorithm complexity. Say, Java doesn't have a single best-for-all Set implementation, you need to pick the one that suits your case.
I didn’t test it, but I believe that there is no problem with calling another class that creates threads. The problem here is about calling the same class’s static methods from another thread from the static initializer. Which you can’t do by a trivial new Foo(), only by this already red flag raising line in the video. (You can fall into this trap by new Foo() that awaits a lambda though, I believe . But I would yet again question that code)
Nonetheless, a compiler warning would be appreciated if it can prove in this specific case that a deadlock can arise.
If you put parallel in your stream for a non-heavy computation, wtf are you doing.
Its clearly an abuse here. Sure they've found an interesting edge case. But it makes sense, the class isn't initialised until the static fields are done. Java's model is providing a strong guarantee that this cannot overlap by two threads, ergo using a parallel stream is a dumb idea.
Now the lambda's abstraction is broken by this, but then to fix, you'd need to put non-capturing lambda's somewhere else.
You didn't get the point I was making. When you call a method, you don't always know what it does. Are YOU PERSONALLY to blame for every problem caused by code you call?
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.
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.