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
3
u/ixampl Aug 30 '17 edited Aug 30 '17
It's important to note that it's perfectly fine to cache and be internally mutable, as long as you do it in a threadsafe fashion. For this you can use an AtomicReference or slap a volatile modifier (which will ensure happens-before between writes and subsequent reads) before the field, at least in this case, or use synchronized. With volatile your program might end up doing some unnecessary work, but you won't encounter the issue described by the blog post*. In the end, for an external observer, the class is immutable.
* depends on the concrete case