Earlier quoted context omitted.
It has been a very long time since I’ve used Java. Rust will tell you where you need the locks, at compile time. Does Java? Serious question.
Not since I’ve use it either. I may be missing something since I’ve only used async Rust, in what way does Rust say “you need a lock here”? If it does that then I stand corrected and I may just have to drop async Rust altogether and checkout crossbeam + rayon that everyone raves about.
Here's some (contrived!) example code (for one thing I'm using thread::scope because I don't want to deal with joining the threads):
use std::thread;
use std::rc::Rc;
fn main() {
let v = Rc::new(vec![1, 2, 3]);
thread::scope(|s| {
s.spawn(|| {
do_work(v.clone());
});
s.spawn(|| {
do_work(v.clone());
});
});
}
fn do_work(v: Rc>) {
unimplemented!()
}
This gives: error[E0277]: `Rc>` cannot be shared between threads safely
--> src/main.rs:8:17
|
8 | s.spawn(|| {
| ___________-----_^
| | |
| | required by a bound introduced by this call
9 | | do_work(v.clone());
10 | | });
| |_________^ `Rc>` cannot be shared between threads safely
|
Rc is not thread-safe. We try to send it into some threads. It doesn't work. Switching to Arc, which does use atomic reference counts and therefore is thread-safe, does. Same principle would apply with Mutex if we were trying to modify the vector, Rust will yell at us.One really really nice thing about this is that it'll check no matter how for "down" into the details the thread unsafety is. There's a story Niko told in a presentation of his how he was doing some refactoring and added a type that wasn't thread-safe like, four or five layers down from where the threading happened. rustc caught it immediately, and therefore, it was obvious. Would have been a heisenbug in other languages.
Async Rust also uses Send/Sync, for example, tokio::spawn requres a Send bound, just like spawning a thread does. I do know there are some tricky deadlock cases there, if I recall? But deadlocking isn't what I'm talking about, no aspect of Rust statically prevents those.