3 ms·
Java data structures are built on top of a pile of unsafe code (the JVM and especially the GC), in a similar manner to building things on top of the std data st
by dbaupp 8y ago
Java data structures are built on top of a pile of unsafe code (the JVM and especially the GC), in a similar manner to building things on top of the std data structures in Rust.
For concurrency in particular the JVM exposes a more restricted (slower) model than the hardware, to guarantee no unsafety no matter how wrong the code is. Rust can't make that trade-off and still reach its performance goals.
- deepsun 8y agoMmm, no, ConcurrentLinkedQueue uses the same RAM primitives as Rust can use (compare-and-set, compare-and-set etc) that are needed to implement concurrent queues. And it doesn't use Unsafe class (same as Rust's "unsafe" keyword) in it, it's easy to check. Or maybe I just miss something?
- dbaupp 8y agoYes: a GC means the programmer can avoid thinking about object lifetimes and just pretend every object lives forever. The garbage collector is deeply unsafe (as in, bugs may cause memory corruption): if a GC fails to account for even a single pointer somewhere, it might deallocate an object too early, potentially leading to problems like use-after-free. Additionally, the JVM ensures every read and write to memory has (minimal) synchronisation so that there is no risk of a data race, meaning no undefined behaviour, no matter how wrong the code is. And, even the reads and writes using proper synchronisation (compare-and-swap, etc.) have only one choice: sequential-consistency. In Rust, a global built-in-to-the-language GC isn't appropriate, and managing object lifetimes properly, with shared memory, is hard. It is thus something that a library has to use `unsafe` for, to assert to the compiler that the programmer has got things right because it is unable to check. Similarly, using synchronised reads/writes everywhere isn't right for Rust, so it is up to the concurrent data structure author to use the right synchronisation (which can be weaker for performance: acquire/release, instead of only SeqCst) just for the rest of the code to be safe: this is also something a compiler can't check.