While I agree it's generally bad practice, there is no technical reason it is an issue. In the static initializer case there is, because it is part of a larger process out of your control.
I've seen plenty of code that does a lot of heavy lifting in the constructor that works fine.
There is no guarantee that the construction of the object has finished. So if you do this, you end in all kinds of trouble. If you work with multithreded applications you especially have to be very careful about constructors and object references with non final fields
There is no guarantee that the construction of the object has finished.
Constructors work the same way methods do, they can just only be called once per object and must be called first. Not sure what you're on about.
It sounds like your describing a constructor that assigns fields asynchronously which I agree would be terrible. But same with any method that returns an object still being initialized in another thread.
Constructors work the same way methods do, they can just only be called once per object and must be called first. Not sure what you're on about.
Try to initialize an object in another thread, while holding a reference to that same object, in the first thread, or leaking `this` in the constructor (adding this to a list eg.), and try to access a non-final field, and see what happens.
The jvm is allowed, to reorder memory operations inside the constructor, to guarantee the initialization of final fields, so saying the constructor is like any other method besides the obvious object initialization, not entirely correct.
So, don't use the constructor like any other method, and don't start doing a parallel stream computation inside it either.
3
u/PerfectPackage1895 Mar 21 '21
This is hardly any better than doing a heavy amount of calculation in the constructor, which also will end bad.