Hacker News new | ask | show | jobs
by cogman10 42 days ago
The problem is concurrent access. A write bit on the value doesn't really help as you have to check and update the bit using atomic instructions. But you'd also need to reserve that bit for every read as concurrent access wouldn't be safe.

That's the tearing problem.

It gets worse because things you can't generally do in the JVM can happen. For example, if your value class contains a reference to an object but that reference just so happens to split a tear, it's possible one thread to see an invalid reference while another thread is writing that object. That could be fixed with some added padding based on the architecture to make sure stored references aren't tearable.

1 comments

References can't tear in Java, per the specification (long and double could actually, the spec only talks about references and 32-bit slots being tear-free - though actually almost all implementations have them atomic as it's practically free on 64-bit CPUs). That would basically make the platform memory unsafe so I'm fairly sure they would make sure references are always written atomically.

But tearing may still cause a logical issue of course. (Think of a date class where the day may still be 31 but the month was set to Feb on another thread).

Interestingly Go is memory unsafe on this issue, slices can tear and later code can read into an incorrect offset from the pointer. Java abstracts away pointers, so this issue is non-existant there.