Hacker News new | ask | show | jobs
by hedora 30 days ago
In java, the caller gets the reference before the constructor runs. It's in the language spec. It's terrible. You can prove it yourself with something like:

   this.dangerous = new Lol();
and then have Lol()'s constructor sleep for 10 sec then set done = true at the end of the contstructor. In another thread:

   while(!this.dangerous) { }
   assert(this.done) // will throw.
I guess you could use double-checked locking as a class author by having every public method on your class do a if (!this.done) { throw; }, and make sure there are no public fields.

That's pretty lame though.

1 comments

That's a data race. The caller gets the reference after the constructor runs, but writes to non-final fields from the constructor might not be visible to other threads.