medium.com 5 min read Original Source

Why Rust Will Not Let You Share This Across Threads

I spent an embarrassing amount of time arguing with the compiler over a function that, in Java, I would have written without thinking twice. Pass a struct into a thread, read it from the main thread at the same time, move on with my life. Rust looked at this plan and refused, citing two traits I had never personally written and barely understood: Send and Sync.

The error messages mention these constantly once you start working with threads, and the explanations online tend to define them in terms of each other in a way that teaches you nothing. Send means a type can be sent between threads. Sync means a type can be shared between threads. Technically true, completely useless until you understand what is actually being checked underneath.

What the compiler is actually verifying

Send and Sync are not features you write code to satisfy directly, most of the time. They are auto traits, which means the compiler derives them automatically based on what a type is made of. If every field inside your struct is Send, your struct is Send. If every field is Sync, your struct is Sync. You do not implement them by hand unless you are doing something unusual, like wrapping a raw pointer.

Think of them as answering two different questions:

Send: can ownership of this value move to another thread safely?

Sync: can multiple threads hold a reference to this value at the same time without anything going wrong?

Most types are Send because moving ownership just means the bytes get handed off and the original thread stops touching them. The danger case is a type like Rc<T>, Rust’s single-threaded reference-counted pointer. Rc keeps an internal counter of how many references exist, and that counter is updated with plain, non-atomic increments. If you move an Rc to another thread while a clone of it sits on the original thread, two threads can increment that counter at the same time with no synchronisation at all. That is a data race, the exact thing Rust’s ownership model exists to prevent. So Rc<T> is explicitly not Send. The compiler will not let you put it in a thread::spawn closure.

<button data-code="use std::rc::Rc;
use std::thread;

fn main() {
let data = Rc::new(42);

let handle = thread::spawn(move || {
println!("{}", data);
// error[E0277]: `Rc` cannot be sent between threads safely
});

handle.join().unwrap();
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::rc::Rc;
use std::thread;

fn main() {
    let data = Rc::new(42);

    let handle = thread::spawn(move || {
        println!("{}", data);
        // error[E0277]: `Rc<i32>` cannot be sent between threads safely
    });

    handle.join().unwrap();
}
use std::rc::Rc;
use std::thread;

fn main() {
    let data = Rc::new(42);

    let handle = thread::spawn(move || {
        println!("{}", data);
        // error[E0277]: `Rc<i32>` cannot be sent between threads safely
    });

    handle.join().unwrap();
}

The important detail is not that Rc is a pointer. It is that the reference count itself is shared mutable state, updated without any of the protection a thread-safe counter would have. That is the actual danger, not the pointer indirection.

Sync is about shared access, not ownership transfer. A type is Sync if &T is Send, meaning a reference to it can safely move between threads. Almost everything immutable is Sync by default, because reading the same memory from multiple threads simultaneously causes no harm. The trouble starts with mutability. Cell<T> and RefCell<T>, Rust’s tools for mutating values through a shared reference in single-threaded code, are explicitly not Sync. They use internal bookkeeping with no atomic operations, so two threads calling borrow_mut() at the same time would race exactly the way the Rc counter does.

Also very important : If this kind of explanation is useful, following gets you the next one when its published

The fix is not a workaround, it is the actual answer

This is where Arc and Mutex stop being “the thing the tutorial tells you to use” and start making sense as a direct response to the two specific problems above. Arc<T>, atomic reference counted, does exactly what Rc<T> does except the increment and decrement operations on the internal counter are atomic CPU instructions. Multiple threads can clone an Arc and drop it concurrently without corrupting the count.

Arc solves the reference-counting problem, not every thread-safety problem. It is only Send and Sync when the value it wraps can also satisfy those guarantees. Wrap a RefCell<T> in an Arc and you still cannot safely share it across threads, because the Arc part is fine but the RefCell part still races.

use std::sync::Arc;
use std::thread;

fn main() {
    let data = Arc::new(42);
    let data_clone = Arc::clone(&data);

    let handle = thread::spawn(move || {
        println!("{}", data_clone); // fine, Arc handles concurrent reference counting
    });

    handle.join().unwrap();
    println!("{}", data); // also fine, both threads can read
}
use std::sync::Arc;
use std::thread;

fn main() {
    let data = Arc::new(42);
    let data_clone = Arc::clone(&data);

    let handle = thread::spawn(move || {
        println!("{}", data_clone); // fine, Arc handles concurrent reference counting
    });

    handle.join().unwrap();
    println!("{}", data); // also fine, both threads can read
}

Mutex<T> solves the second problem. Wrapping a value in a Mutex gives every thread a way to get exclusive, synchronised access before reading or writing, using an OS-level lock instead of the unsynchronised bookkeeping that RefCell relies on. Mutex<T> is Sync as long as T is Send, which is precisely the guarantee you need to share mutable state across threads.

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap()); // 10, no race possible
}
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap()); // 10, no race possible
}

The combination Arc<Mutex<T>> shows up constantly in real Rust concurrency code, and once you understand Send and Sync properly, the reason stops being “this is the pattern everyone uses” and becomes “this is the one of the fundamental combination of primitives that actually satisfies both constraints at once.”

What this looks like in Java by comparison

Java does not have an equivalent concept checked by the compiler, and that difference is the important point. You can share any object across threads in Java with no restriction whatsoever. HashMap, ArrayList, your own plain class, all of it. Whether that sharing is safe is left entirely to you, documented (if you are lucky) in a comment or a Javadoc note saying “this class is not thread-safe,” discovered (if you are unlucky) in production under load.

ConcurrentHashMap exists in Java precisely because HashMap is not safe to share, and the compiler has no way of stopping you from sharing a regular HashMap anyway. You find out the hard way, usually through a ConcurrentModificationException or silently corrupted data that takes a debugging session to trace back to its source. Rust’s equivalent failure happens at compile time, with a specific error naming the exact type that is not Send or not Sync, before the program runs even once.

That doesn’t make Rust universally better at concurrency. It is a specific, narrow claim: the category of bug where you share mutable state across threads without synchronisation and only discover it under real concurrent load is a category Rust eliminates at compile time for safe code, because Send and Sync make the property checkable rather than something you have to remember and document correctly every single time.

Why the auto-derivation matters more than it looks

The fact that Send and Sync propagate automatically through composition is the part that makes this genuinely useful day to day rather than just theoretically interesting. You do not annotate every struct you write with Send or Sync. You write your struct, and the compiler figures out whether it is safe to share based on what is inside it. The moment you put an Rc<T> or a RefCell<T> inside a struct that previously had neither, that struct silently loses Send or Sync, and the very next time you try to send it across a thread boundary, the compiler stops you immediately with an error pointing at the exact field responsible.

That feedback loop, change a field, immediately find out if it broke thread safety, without writing a single concurrency test, is the actual value here. It turns a class of bug that normally only shows up under load in production into a compile error that shows up the moment you save the file.

The quick reference

<button data-code="- Need to move ownership to another thread? Send.
– Need to share immutable references across threads? Sync.
– Need to share mutable state across threads? Arc<Mutex>.
– Need interior mutability but only on one thread? RefCell.
– Need shared ownership but only on one thread? Rc.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

- Need to move ownership to another thread? Send.
- Need to share immutable references across threads? Sync.
- Need to share mutable state across threads? Arc<Mutex<T>>.
- Need interior mutability but only on one thread? RefCell<T>.
- Need shared ownership but only on one thread? Rc<T>.
- Need to move ownership to another thread? Send.
- Need to share immutable references across threads? Sync.
- Need to share mutable state across threads? Arc<Mutex<T>>.
- Need interior mutability but only on one thread? RefCell<T>.
- Need shared ownership but only on one thread? Rc<T>.

If thread safety in Rust is something you keep circling back to, the field guide covers the full concurrency model from ownership through to Arc, Mutex, and channels.

$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample