4 ms·
It'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
by hyperpape 9y ago
It'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.