3 ms·
I am a complete java noob, but it seems like in the test program the same variable testBigDecimal is being shared by different threads without any lock or mutex
by dingo_bat 9y ago
I am a complete java noob, but it seems like in the test program the same variable testBigDecimal is being shared by different threads without any lock or mutex or any sort of concurrency control! Won't any function working on testBigDecimal be thread unsafe if it was not specifically written assuming it was working on a shared object? Why is this news?
Disclaimer: I am so java illiterate that I am applying my C understanding to the code snippet.
- hyperpape 9y agoIt's immutable, and immutable objects are thread safe. This is also true in C: you can safely pass references to structs between threads with no locks, as long as you never mutate them. Java just enforces that immutability if you write the class the right way. ...the bug is that it's not really immutable, insofar as it's using an unsafe mutation under the hood to implement its toString method. So it either needs to document the fact that it's not immutable despite the appearance otherwise (crazy), or fix the problem.
- _pmf_ 9y ago> you can safely pass references to structs between threads with no locks, as long as you never mutate them. Isn't it required to perform a safe handoff?
- cesarb 9y agoThe rules for C and Java are different. In Java, it's guaranteed that the assignments in the constructor to fields marked as final is visible to other threads before the newly constructed object is (unless you stash a reference to it before returning to the constructor), but C has no such guarantee, so in C you have to put the memory barriers yourself.
- hyperpape 9y agoYes, what Java gives you for immutable objects is a guarantee of safe publication. In both languages, once you have the object published, you can freely share it between threads.
- scatters 9y agoBigDecimal claims to be an immutable class, with only non-mutating public methods. In C, the equivalent would be that every exposed function takes `const BigDecimal *`. Even in C, it is fine for multiple threads to access the same data as long as they all read and don't write it.
- dfox 9y agoBigDecimal does not contain any mutable user visible state, so it should be usable by different threads without synchronisation of any kind (except the implicit synchronisation by means of "can I see pointer to that instance") It is news because either there is bug in the BigDecimal or JVM in question that causes the above assumption to not hold.