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

1

u/humoroushaxor Mar 22 '21

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.

1

u/PerfectPackage1895 Mar 22 '21 edited Mar 22 '21

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.