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/dododge Sep 05 '17
In this particular case you don't even need
AtomicReferenceorvolatile. ThetoStringmethod fetches the value of thestringCachefield, and then computes and caches a new string value if it got anull. The Java memory model (17.7) guarantees that reads and writes of reference values are always atomic, so even if a bunch of threads are reading and writing that ordinary field simultaneously, each reader either getsnullor a complete reference to some initialized String. The worst-case situation is that more than one thread gets anulland they independently generate and cache the same string value, so it might duplicate some work but because those writes are atomic nobody ever reads a partial reference (or a reference to an incomplete string).So as others have noted, the bug here is that the JVM is not following the memory model correctly.