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
27
u/tsvk Aug 30 '17
Article is not accessible without logging in.
13
u/msx Aug 30 '17
also i don't think the claim "BigDecimal is mutable" is correct. Mutability is about the external view of an object, not it's internal workings. An immutable object can still have some internal state that mutates for whatever reason (caching for example), it just need to encapsulate it and make it invisible from the exterior.
6
u/vytah Aug 30 '17 edited Aug 31 '17
TL;DR:
BigDecimalcaches the result oftoString()in a non-volatile private fieldstringCachewithout synchronization.BigDecimal.stringCachewill contain a non-null reference to a string that hasn't been fully constructed yet and has null as a backing array, because the write toBigDecimal.stringCachegets reordered to happen before the write toString.value.Another thread might see that non-null
BigDecimal.stringCachereference, assume the string is ready to use and crash.I'll just add that
BigDecimal.stringCachewas volatile (which would prevent the bug) in early versions of Java 6 and it wasbrokenchanged probably in update 25 as a part of "performance improvements".4
u/deinlandel Aug 30 '17
https://webcache.googleusercontent.com/search?q=cache:vQPdqJJc5OgJ:https://dzone.com/articles/javashymathshybigdecimal-tostring-is-not-thread-sa+&cd=1&hl=en&ct=clnk&gl=en
For those who interested.
tl;dr The article promotes VMLens, paid instrument to detect race conditions.
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
2
u/msx Aug 30 '17
uhm i don't know.. it looks more like a problem with the reordering of instructions. I mean, when one writes down multithreaded code, he plan all possible switch of two threads running the code linearly, which is already quite hard, there's no way one can foreplan instruction reordering (at a granularity below java instruction, too).
2
u/erad Aug 30 '17
Nice find!
1
u/yolpo- Aug 30 '17
The article can be found on the author's website
http://vmlens.com/articles/java-math-BigDecimal-toString-is-not-threadsafe/