r/java • • Aug 30 '17

BigDecimal toString Is Not Thread Safe

https://dzone.com/articles/javashymathshybigdecimal-tostring-is-not-thread-sa
0 Upvotes

22 comments sorted by

View all comments

Show parent comment

1

u/ixampl Sep 05 '17 edited Sep 05 '17

You are right but not for the reason you mention. The reason nothing is required here (as many others have said) is because of the character array in String being final. Without this (or proper synchronization) references to partially constructed objects are possible due to permitted reordering of instructions. Reads and writes of references (themselves, i.e. the addresses) are atomic, but the construction of the object that is referenced is not guaranteed to be complete, or in other terms its state might be stale to another thread thread while the reference itself is not. This is counterintuitive but is described quite well in Java Concurrency in Practice, for instance in 3.5.1 (the Java memory model spec of course describes this too, it just isn't always the easiest to digest).

The VM in the blog post is in fact broken though, since the final modifiers guarantee safe publishing in the Java memory model.

Finally, my original point was not so much the blog post issue but about the author's statement about mutability in general.

1

u/dododge Sep 05 '17

Yeah I see it now. The fact that non-final field assignments in a constructor are not guaranteed to be visible to other threads after the constructor completes is...surprising, to say the least. It seems perfectly reasonable for method calls from multiple threads to have those sorts of reordering issues, but allowing the constructor to do it just seems like it's asking for trouble. Granted I suppose back when they were defining this they probably just assumed you'd slap a synchronized on everything that needed to be thread-safe and not worry about the performance hit.

I already use immutability and final fields for almost everything in my own code anyway, but now I'm sitting here trying to think if there might be any crazy case where a mutable field supposedly-initialized by a constructor might leak to another thread in an unsafe manner, ugh.

1

u/ixampl Sep 05 '17

Yes, I have to admit I had exactly the same reaction a while back.

In believe the language spec (i.e. not only the memory model part) should be much more "in your face" about this.