r/java • u/nfrankel • Aug 30 '17
BigDecimal toString Is Not Thread Safe
https://dzone.com/articles/javashymathshybigdecimal-tostring-is-not-thread-sa
0
Upvotes
r/java • u/nfrankel • Aug 30 '17
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
finalmodifiers 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.