What is an actor and how does it prevent data races
Actor isolation as compiler-enforced safety.
Actors serialize access to mutable state, reachable only via await; compiler blocks unsafe access. Token-refresh actor coalesces concurrent refreshes.
WHAT THIS TESTS This probes your understanding of actor isolation as a compile-time safety guarantee, and whether you can apply it to a real concurrency hazard rather than reciting a definition.
A GOOD ANSWER COVERS An actor is a reference type that protects its mutable state by guaranteeing only one task executes its isolated methods at a time. Access from outside the actor must be awaited, because the call may suspend until the actor is free. The key advantage over locks or a serial DispatchQueue is enforcement: the compiler refuses to let you touch isolated state without going through the actor, so you cannot accidentally read shared state on the wrong thread. Locks rely on every caller remembering to lock; actors make the mistake impossible.
COMMON WRONG ANSWERS Describing an actor as merely a wrapper around a lock or a serial queue, missing the compiler enforcement. Forgetting actor reentrancy: an actor can interleave another task at every await point, so invariants must hold across awaits. Assuming an actor guarantees ordering of all callers, which it does not.
LIKELY FOLLOW-UPS What reentrancy means and how it can cause two callers to both trigger a token refresh. The fix is to store an in-flight refresh Task and await it instead of starting a new one. The difference between actor and @MainActor. When to use nonisolated for state that needs no protection, like a constant.
ONE CONCRETE EXAMPLE You build an actor TokenStore holding the current access token. A validToken() method checks expiry; if expired, it must refresh. Because of reentrancy, two requests calling validToken() concurrently could each start a refresh. So TokenStore keeps a private refreshTask: Task<Token, Error>? property. The first caller creates the task and stores it; the second sees a non-nil task and awaits the same one. Both receive a single refreshed token, the network sees one refresh call, and all access to the token is serialized and race-free without any manual locking.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.