Language-Level Concurrency and Multithreading Questions
Per-language and per-runtime concurrency: the threading and async APIs each language and platform provides (goroutines, channels, worker pools and pipelines in Go, threads, executors, ThreadPoolExecutor tuning and CompletableFuture in Java, Kotlin coroutines, dispatchers, Flow and structured concurrency, Swift GCD with queues and QoS, DispatchGroup, OperationQueue, actors and async/await, Android Handler/Looper, HandlerThread and thread pools, Flutter isolates, C++ std::thread and atomics, Python threads versus multiprocessing versus asyncio tasks, gather and graceful shutdown), each language's memory model and visibility guarantees (Java happens-before and volatile, C++11 memory orders such as relaxed, acquire and release, Objective-C and Swift atomic versus nonatomic), mobile main-thread rules and JNI thread attachment, cancellation and shutdown idioms, and the idioms for coordinating shared state safely in that language, including thread-safe caches, singletons and bounded queues. Also covers reproducing, testing and diagnosing races and deadlocks in a specific language or app, and migrating callback, GCD or thread-pool code to structured concurrency. Covers choosing and using a language's concurrency primitives correctly. Boundary: general synchronization theory, deadlock and lock-free algorithm internals, OS scheduling, database isolation levels, and callback or event-loop architecture are covered elsewhere.
In Swift, show how to use OperationQueue to execute background operations while limiting concurrency to a maximum of 3 concurrent operations, and how to set dependencies between operations so a final UI update only runs after others complete.
Sample Answer
Direct answer
Create one OperationQueue, set maxConcurrentOperationCount = 3, and add the background work as Operation objects. Give the final UI update its own BlockOperation, call uiUpdate.addDependency(op) for every background operation, and add that UI operation to OperationQueue.main. The queue will not start an operation until every operation it depends on has finished, so the UI update cannot start early, and because it sits on the main queue, it runs on the main thread where UI code is allowed.
Terms used here: an operation queue is Foundation's object-oriented layer over Grand Central Dispatch (GCD, Apple's thread-pool and queue system); an Operation is one unit of work that can have dependencies, a priority, and can be cancelled; the main thread is the only thread allowed to touch UIKit or SwiftUI views. OperationQueue.main is the main queue: a serial queue whose operations always run on the main thread (a queue is where work waits; a thread is what runs it). A BlockOperation is a ready-made Operation that runs one or more closures; you subclass Operation yourself only when you need custom start, finish or asynchronous behaviour.
Complete code
import Foundation
// Thread-safe tracker for how many operations run at once.
final class Gauge: @unchecked Sendable {
private let lock = NSLock()
private var current = 0
private(set) var peak = 0
func enter() { lock.lock(); current += 1; peak = max(peak, current); lock.unlock() }
func leave() { lock.lock(); current -= 1; lock.unlock() }
}
// Shared results: every access goes through the lock.
final class Results: @unchecked Sendable {
private let lock = NSLock()
private var values: [Int: String] = [:]
func set(_ key: Int, _ value: String) { lock.lock(); values[key] = value; lock.unlock() }
var count: Int { lock.lock(); defer { lock.unlock() }; return values.count }
}
let gauge = Gauge()
let results = Results()
let background = OperationQueue()
background.name = "downloads"
background.maxConcurrentOperationCount = 3 // at most 3 operations execute at once
background.qualityOfService = .utility
// The "UI update" runs on the main queue, so UI code is safe in it.
let uiUpdate = BlockOperation {
let count = results.count
print("UI update on main thread: \(Thread.isMainThread), results ready: \(count)")
print("peak concurrent background operations: \(gauge.peak)")
exit(0)
}
var work: [Operation] = []
for i in 1...8 {
let op = BlockOperation {
gauge.enter()
Thread.sleep(forTimeInterval: 0.2) // stand-in for a network call
results.set(i, "payload-\(i)")
gauge.leave()
}
uiUpdate.addDependency(op) // uiUpdate waits for every op
work.append(op)
}
background.addOperations(work, waitUntilFinished: false)
OperationQueue.main.addOperation(uiUpdate) // main queue holds it until dependencies finish
RunLoop.main.run(until: Date(timeIntervalSinceNow: 10))
print("timed out")
In the sample, Sendable is the Swift marker for a type that is safe to share between concurrent code, and @unchecked Sendable tells the compiler to trust that claim without checking, which is acceptable here only because every access to the fields of Gauge and Results goes through an NSLock. A plain Swift dictionary is not safe for concurrent writes, hence the lock inside Results. (Language mode matters here: keeping the shared state as a top-level NSMutableDictionary global would compile in Swift 5 language mode but be rejected in Swift 6 mode (swiftc 6.0.3 reported main actor-isolated let 'store' can not be referenced from a nonisolated context, because top-level variables in main.swift are main-actor isolated and the @Sendable operation closure runs elsewhere). Wrapping the state in a lock-protected Sendable class works in both modes.) A command-line program exits as soon as its top-level code ends, and main-queue operations only run while the main run loop (the loop that waits for and dispatches events and main-queue work) is spinning, so RunLoop.main.run(until:) keeps the process alive long enough for uiUpdate to run, and exit(0) inside it ends the demo early. A real app already has a running main run loop.
Compiled with swiftc -swift-version 5 main.swift and with swiftc -swift-version 6 main.swift in a swift:6.0 container (Swift 6.0.3, Linux aarch64) and run repeatedly with several cores available, both language modes printed these two lines on every run:
UI update on main thread: true, results ready: 8
peak concurrent background operations: 3
The peak is read from a counter that every operation increments on entry and decrements on exit, so it is a measurement of overlap, not an assumption. The cap is an upper bound, not a promise of three: the peak never exceeds 3, but how many operations really overlap depends on how many worker threads the dispatch runtime starts. In the same container pinned to a single CPU the program reported a lower peak than 3, and with two CPUs the peak line varied between runs, so the line above is what to expect only on a machine with spare cores. Raising the cap to 5 made the same program report 5 on a machine with at least five spare cores (restricted to four CPUs it reported 4, limited by the workers available rather than by the cap), which shows the counter can catch a limit that is not enforced. With three workers actually running, eight operations at 0.2 s each with at most 3 at a time run in three rounds (3, 3, 2), so the work takes about 0.6 s instead of 1.6 s serially. Timeline under that assumption, with each operation lasting 0.2 s: from 0.0 s operations 1 to 3 run; at about 0.2 s they finish and operations 4 to 6 start; at about 0.4 s operations 7 and 8 run with one slot idle; at about 0.6 s all eight have finished, uiUpdate becomes ready and runs on the main thread. Serial would be 8 times 0.2 s = 1.6 s. On Linux the sample uses NSLock and a RunLoop to keep the process alive; on iOS you would use the app's own run loop and update a view model instead of calling exit(0).
Why each line is there
maxConcurrentOperationCount = 3is the throttle. The queue starts a new operation only when fewer than 3 are running. Setting it to 1 makes the queue serial, which is also a simple way to protect one resource. The documented default lets the system choose, so set it explicitly when you need a hard cap, for example to avoid opening ten simultaneous connections to one server. Note that this is an upper bound; the system may still run fewer.uiUpdate.addDependency(op)is a dependency edge. An operation becomes ready only when all its dependencies have finished. Dependencies work across queues, which is why the background operations and the main-queue operation can be linked.- The
resultsstore is shared by up to 3 threads, so it guards its dictionary with a lock. Operation dependencies order the start ofuiUpdate; they do not make concurrent writes between siblings safe. qualityOfService = .utility(QoS is the priority hint the system uses to schedule threads) tells the system this is long-running work the user is not blocked on, so it can be scheduled below user-interactive work.
Pitfalls that a dependency graph does not protect you from
- Cycles deadlock silently. If A depends on B and B depends on A, neither becomes ready and the queue never runs them. Run in the same container, this code:
import Foundation
let q = OperationQueue()
let a = BlockOperation { print("a runs") }
let b = BlockOperation { print("b runs") }
a.addDependency(b)
b.addDependency(a) // cycle: a waits for b, b waits for a
q.addOperations([a, b], waitUntilFinished: false)
Thread.sleep(forTimeInterval: 1.0)
print("a.isFinished=\(a.isFinished) a.isReady=\(a.isReady) b.isFinished=\(b.isFinished) b.isReady=\(b.isReady)")
print("queue operationCount=\(q.operationCount)")
printed:
a.isFinished=false a.isReady=false b.isFinished=false b.isReady=false
queue operationCount=2
Neither "a runs" nor "b runs" appears, and nothing was reported. Build dependencies in one direction only (workers to final step).
- "Finished" includes cancelled. Run in the same container, a dependent operation whose prerequisite was cancelled before it started still ran:
import Foundation
let q = OperationQueue()
q.maxConcurrentOperationCount = 3
let a = BlockOperation { print("a runs") }
let b = BlockOperation { print("b runs") }
let done = BlockOperation { print("done runs; a.isCancelled=\(a.isCancelled) b.isFinished=\(b.isFinished)") }
done.addDependency(a); done.addDependency(b)
a.cancel() // cancelled before it starts
q.addOperations([a, b, done], waitUntilFinished: true)
which prints:
b runs
done runs; a.isCancelled=true b.isFinished=true
So the final UI step must check for failures itself (for example by reading a results array that failed operations leave empty), rather than assuming all prerequisites succeeded.
- Add dependencies before adding the operation to a queue. Wiring the graph first, as the code does, means the queue never sees a half-built graph. Adding a dependency to an operation that is already running is not a supported way to delay it.
- Async work inside an operation. A
BlockOperationis finished when its block returns. If the block starts a network call with a completion handler and returns, the operation is already finished and the UI update fires too early. For callback-style work, either block the operation's thread with a semaphore (acceptable on a background queue with a small limit) or subclassOperation, overrideisAsynchronous, and manageisExecutingandisFinishedyourself. With Swift concurrency available, aTaskGroupis usually simpler than a custom asynchronousOperation. - Do not call
waitUntilFinishedfrom the main thread on the background queue; it blocks the UI.
When to choose this over alternatives
Pick OperationQueue when you need a concurrency cap, cancellation of individual items, or a dependency graph. For a simple "run three things, then continue" without a cap, DispatchGroup is lighter. For new code on iOS 13 and later with async/await, a withTaskGroup with a bounded number of in-flight child tasks gives the same shape, and in Swift 6 language mode the compiler checks the data-race safety of what the child tasks capture.
A complex intermittent deadlock involves a background sync thread pool, a SQLite wrapper using a single connection, and UI code that sometimes performs synchronous DB reads on the main thread. Propose a root-cause analysis plan listing which thread dumps and lock-orderings to inspect, and recommend architectural and code changes to eliminate deadlock while preserving responsiveness. Provide an example of safe DB access code that avoids blocking the main thread.
Sample Answer
Direct answer
Treat it as a wait-for cycle hunt, in this order: (1) capture every thread's stack while the app is actually hung, (2) write down, for each blocked thread, what it holds and what it waits for, and look for a cycle, (3) reproduce on demand with timeouts and a lock-order checker, (4) fix by giving the single connection one owner and making every UI read asynchronous, so no thread ever blocks waiting for it, (5) prove the fix with a stress harness. The architecture change matters more than any single lock fix: the root cause is that the main thread and a worker pool compete synchronously for one resource.
Terms
A deadlock is a set of threads each waiting for something another thread in the set holds, so none can proceed. A wait-for graph draws an arrow from a thread to the thread holding what it wants; a cycle means deadlock. Lock ordering is a rule that every thread takes locks in the same global order, which makes a cycle impossible. A thread dump (stack trace of every thread) shows where each thread is stopped. A main thread hang on mobile also surfaces to users as a frozen UI, or an ANR (Application Not Responding) on Android.
Step 1: capture thread dumps at the moment of the hang
- iOS: attach the debugger, pause, and run
thread backtrace allinlldb. Look at the main thread and every sync worker. - Android: after an ANR, Android writes trace files on the device; Android's documentation shows
adb root,adb shell ls /data/anrandadb pull /data/anr/<filename>(older releases use one/data/anr/traces.txt). From the field,ApplicationExitInfo(an Android API that lets the app ask the system why its previous process ended; Android 11 and later) reports app exits including ANRs. During development, StrictMode flags accidental I/O on the main thread. - Capture at least three dumps, a few seconds apart. A thread that is in the same frame in all of them is stuck, not just slow.
Step 2: read the dumps as a wait-for graph
For each thread note: the frame where it is parked (lock acquire, dispatch_sync, semaphore wait, synchronized, Object.wait), what it already holds, and what it waits for. Then check the shapes this scenario can take:
- Lock-order inversion (ABBA). Thread 1 takes lock A and then wants lock B; thread 2 takes lock B and then wants lock A. Each holds what the other needs, so neither can move. Here A is the state lock and B the connection: the sync worker holds the state lock and wants the connection; the main-thread read holds the connection and wants the state lock. The demo below produces exactly this.
- Pool starvation. A concrete case: a pool has 4 threads. Thread P1 holds the connection and, inside its transaction, submits a sub-task to the same pool and waits for its result. Threads P2, P3 and P4 are each blocked waiting for the connection. The sub-task is queued but no pool thread is free to run it, so P1 never finishes and never releases the connection. There is no second lock; the cycle goes through the thread pool.
- Main-thread hop. A worker holding the connection calls into the main thread synchronously (
DispatchQueue.main.sync, or on AndroidrunOnUiThreadplus a latch that the worker waits on) while the main thread waits for that connection. The worker waits for the main thread, and the main thread waits for the worker.
Inspect, in the source, every place that acquires the connection and every place that does something else while holding it (callbacks, logging that touches the UI, a second lock, a pool submit). List the acquisitions as an ordered table (lock A then B, per code path). Two paths with opposite orders are the bug. Also grep for synchronous main-thread database reads: sync, runBlocking, .get() on a future, allowMainThreadQueries.
Step 3: make it reproducible
An intermittent deadlock hides until timing lines up. In debug builds, wrap lock acquisition in a timed acquire (for example NSLock.lock(before:)) and when it times out dump all stacks and fail loudly. Add a lock-order checker that records the order each thread takes locks and asserts on an inversion even when the timing did not deadlock this run. Run the sync under a stress test with many workers and main-thread reads firing at random times.
Step 4: fix
Code level:
- One global lock order, written next to the lock declarations, and no callbacks, no UI work, no other lock acquisitions while the connection is held.
- Keep transactions short; never hold the connection across network I/O.
Architecture level:
- Give the connection to one owner: an actor or serial queue on iOS, Room's single database object with suspend DAO functions on Android (Room is Android's SQLite wrapper library, and a DAO, data access object, is the interface where you declare the queries). Android's documentation says Room does not support database access on the main thread, so DAO queries must be asynchronous:
suspendfunctions for one-shot queries andFlowfor observable ones. - The UI observes data (a
Flow, or an actor-backed model updated from the owner) and never performs a synchronous read. - If read latency under writes matters, SQLite's WAL mode (write-ahead logging: writes are appended to a separate log file and merged into the database later, so readers can keep reading the old data meanwhile) allows readers and a writer to proceed at once. SQLite's documentation says readers do not block writers and a writer does not block readers (it adds that this is mostly true), and that only one writer exists at a time. Use separate read connections only if you need that concurrency, because every extra connection reintroduces the question of who waits for what.
Safe DB access example, run
The Swift below was compiled with Swift 6.0.3 in a swift:6.0 Linux container (aarch64), in Swift 5 language mode (-swift-version 5) because the demo uses a global mutable array. Part 1 reproduces the ABBA deadlock with timed acquires. The two semaphores exist only to force the bad timing: syncHasState is signalled once the sync worker holds the state lock, and uiHasConnection once the UI stand-in holds the connection, and each thread waits for the other's signal before asking for its second lock. Without them one thread might finish both acquisitions before the other starts, and the deadlock would not appear. The lock(before:) timeouts let each thread give up after 1 s and report instead of hanging forever. Part 2 is the fix: an actor stands in for the single connection, eight background tasks queue 800 writes of 2 ms each, and the "UI" awaits reads without ever blocking a thread.
import Foundation
// ---------- Part 1: the deadlock, with timeouts so the demo can report it ----------
let stateLock = NSLock() // protects sync bookkeeping (pending uploads, cursors)
let connectionLock = NSLock() // the single SQLite connection
let syncHasState = DispatchSemaphore(value: 0)
let uiHasConnection = DispatchSemaphore(value: 0)
let report = NSLock()
var lines: [String] = []
func log(_ s: String) { report.withLock { lines.append(s) } }
let group = DispatchGroup()
DispatchQueue.global().async(group: group) { // background sync worker
stateLock.lock() // order: state, then connection
syncHasState.signal(); uiHasConnection.wait()
if connectionLock.lock(before: Date().addingTimeInterval(1)) {
connectionLock.unlock(); log("sync: got both locks")
} else { log("sync: stuck waiting for the connection while holding state") }
stateLock.unlock()
}
DispatchQueue.global().async(group: group) { // stands in for the UI thread's synchronous read
connectionLock.lock() // order: connection, then state
uiHasConnection.signal(); syncHasState.wait()
if stateLock.lock(before: Date().addingTimeInterval(1)) {
stateLock.unlock(); log("ui: got both locks")
} else { log("ui: stuck waiting for state while holding the connection") }
connectionLock.unlock()
}
group.wait()
let stuck = lines.filter { $0.contains("stuck") }.count
print("threads stuck for the full 1 s timeout (at least 1 means deadlock):", stuck >= 1)
// ---------- Part 2: one owner for the connection, no thread ever blocks on it ----------
actor Database {
private var rows: [String: Int] = [:] // stands in for the SQLite connection
func read(_ key: String) -> Int? { rows[key] }
func write(_ key: String, _ value: Int) {
usleep(2_000) // a 2 ms transaction
rows[key] = value
}
}
let db = Database()
// Background sync: many concurrent tasks, each takes turns on the actor.
let syncTask = Task {
await withTaskGroup(of: Void.self) { g in
for w in 0..<8 {
g.addTask { for i in 0..<100 { await db.write("k\(w)", i) } }
}
}
}
// "UI": reads are awaited, never blocking the thread that issues them.
var worstMs = 0.0
var reads = 0
for _ in 0..<200 {
let t0 = Date()
_ = await db.read("k0")
worstMs = max(worstMs, Date().timeIntervalSince(t0) * 1000)
reads += 1
try await Task.sleep(nanoseconds: 1_000_000)
}
await syncTask.value
print("reads completed:", reads)
print("final k0:", await db.read("k0") ?? -1)
print(String(format: "worst read latency while 800 writes queue up: %.1f ms", worstMs))
On a sample run it printed:
threads stuck for the full 1 s timeout (at least 1 means deadlock): true
reads completed: 200
final k0: 99
worst read latency while 800 writes queue up: 39.5 ms
The first line is true by construction: the semaphores force each thread to hold its first lock before either asks for its second, so at least one of them always times out. The lines array records which thread reported "stuck". Both threads start waiting at nearly the same moment, so both can time out; but when one times out slightly earlier it releases its first lock and the other then succeeds and logs "got both locks", so only one "stuck" line appears. Which of the two outcomes you get, and which side reports, depends on timing and on how many CPUs are available (with several CPUs both threads can report "stuck", while with one CPU a single "stuck" line is the usual result). That is why the test prints whether at least one thread was stuck rather than how many, and why a real deadlock that depends on timing like this looks intermittent in production. The worst awaited read took tens of milliseconds and varied from run to run: the read queues behind pending writes inside the actor, but no thread is blocked, so the UI thread keeps drawing. If a delay of that size matters to a screen, serve it from an in-memory copy the owner updates, or add a read connection under WAL.
Android equivalent:
// Room runs suspend DAO queries off the main thread for you. @Upsert (Room 2.5.0 and later) inserts a row, or updates it if the key already exists.
@Dao interface SyncDao {
@Query("SELECT * FROM item WHERE id = :id") suspend fun item(id: Long): Item?
@Query("SELECT * FROM item ORDER BY updatedAt DESC") fun observeItems(): Flow<List<Item>>
@Upsert suspend fun upsertAll(items: List<Item>)
}
class ItemRepository(private val dao: SyncDao, private val io: CoroutineDispatcher = Dispatchers.IO) {
val items: Flow<List<Item>> = dao.observeItems() // UI collects this; no blocking read
suspend fun sync(remote: List<Item>) = withContext(io) { // network parsing off the main thread
dao.upsertAll(remote) // one short write
}
}
Verify the fix
- Run the same stress harness against the old and new code; the old one must hang or time out at least once so you know the test can fail.
- On iOS run it under Thread Sanitizer; on Android run with StrictMode enabled and fail the test on a main-thread violation.
- In production watch the ANR rate or hang rate and the p95 of database call duration for two releases after the change.
Common mistakes
- Fixing one lock order and leaving the main-thread synchronous read, so pool starvation still deadlocks.
- Increasing the pool size to hide starvation.
- Adding a second connection without deciding who waits for whom.
Compare the trade-offs of using a serial DispatchQueue, NSLock, and the Swift actor model to protect shared mutable state. For each approach describe performance characteristics, fairness, deadlock risk, composability, and Objective-C interoperability considerations and give an example scenario where it would be the preferred solution.
Sample Answer
Recommendation first
For new Swift code, default to an actor for state that is touched from async code. Use an NSLock (or OSAllocatedUnfairLock) for a tiny, hot critical section that synchronous code or Objective-C must call. Use a serial DispatchQueue when you need strict first-in-first-out ordering of operations, fire-and-forget writes, or you are inside an existing GCD (Grand Central Dispatch, Apple's queue-based concurrency library) code base. Terms: OSAllocatedUnfairLock is a lightweight lock type from Apple's os module. An actor is a Swift reference type whose mutable state can only be touched by one caller at a time, enforced by the compiler; a serial queue runs submitted blocks one after another; NSLock is a mutual-exclusion lock. The comparison uses four words precisely. Fairness: whether waiting callers are served in the order they arrived. Composability: whether two individually correct operations can be combined into a correct larger one. Isolation: the compiler rule that only code running on the actor may touch its state. Reentrancy: while an actor method is suspended at an await, other calls to the same actor may run (shown in the example below).
Comparison
Serial DispatchQueue | NSLock | actor | |
|---|---|---|---|
| Performance | Each operation is a block dispatched to a queue. async returns quickly but costs an allocation and a later hop; sync makes the caller wait. | Lock and unlock are a few instructions when uncontended; the caller does the work on its own thread. | A call from outside is an await: the task may suspend and resume on the actor's executor (the serial context that runs the actor's code). Cheap for coarse operations, wasteful for one-integer updates. |
| Fairness | FIFO: blocks start in the order they were submitted. | No ordering promise; a thread that releases and relocks can beat waiters. | Not guaranteed FIFO. SE-0306 (the Swift Evolution proposal that introduced actors) says tasks awaiting an actor are not guaranteed to run in the order they awaited it, and that the runtime aims to avoid priority inversions, using techniques such as priority escalation. |
| Deadlock risk | sync onto the queue you are already running on traps. A sync cycle between two queues deadlocks. | Not reentrant: locking twice on one thread deadlocks (NSRecursiveLock exists). Two locks taken in different orders deadlock. | No lock-order deadlock inside one actor, and no self-deadlock, but it has the reentrancy problem below. Because an actor gives up its isolation while suspended at an await, two actors that await each other do not deadlock the way two locks do (the two-actor run below completes); a stall needs code that blocks a thread inside an actor, such as DispatchSemaphore.wait(), or an await on something that never completes. |
| Composability | Blocks submitted from many places stay ordered; a queue can be told to run its blocks on another queue, so several queues can share one underlying serial queue. Hard to know from a call site that a queue is involved. | Poor: you cannot combine two locked operations into one without exposing the lock, and the compiler will not check you hold it. | Best compiler support: isolation is part of the type, and misuse is a compile error in Swift 6 mode. But multi-step logic must tolerate interleaving at each await. |
| Objective-C interop | Fully usable. | Fully usable. | Members can be exposed to Objective-C only if they are async or not isolated to the actor (SE-0306). A synchronous actor method such as func balance() -> Int cannot be marked @objc, so Objective-C code cannot call it; if Objective-C must read the state synchronously, that points to a lock or a queue. |
| Preferred for | Ordered event processing, a log or analytics writer, legacy GCD APIs that already take a queue. | A hot counter, a small cache, state read from synchronous or Objective-C code. | A repository, session store or download manager used from async code. |
Evidence from runs
The programs below were compiled in a swift:6.0 container (Swift 6.0.3, aarch64 Linux) with swiftc -O -swift-version 6.
Cost of one operation. This program updates a counter 1,000,000 times from one thread (no contention) through each mechanism and prints the average time per update:
import Foundation
final class LockCounter: @unchecked Sendable { // @unchecked Sendable: the lock makes it safe, the compiler cannot check that
private let lock = NSLock()
private var n = 0
func inc() { lock.lock(); n += 1; lock.unlock() }
}
final class QueueCounter: @unchecked Sendable {
private let q = DispatchQueue(label: "counter")
private var n = 0
func incSync() { q.sync { n += 1 } }
func incAsync() { q.async { self.n += 1 } }
func drain() -> Int { q.sync { n } } // waits until every queued block has run
}
actor ActorCounter {
private var n = 0
func inc() { n += 1 }
}
func ns(_ body: () -> Void) -> Double {
let t0 = DispatchTime.now().uptimeNanoseconds
body()
return Double(DispatchTime.now().uptimeNanoseconds - t0)
}
@main
struct Bench {
static func main() async {
let N = 1_000_000
let lc = LockCounter()
let a = ns { for _ in 0..<N { lc.inc() } }
let qc = QueueCounter()
let b = ns { for _ in 0..<N { qc.incSync() } }
let qa = QueueCounter()
let c = ns { for _ in 0..<N { qa.incAsync() }; _ = qa.drain() }
let ac = ActorCounter()
let t0 = DispatchTime.now().uptimeNanoseconds
for _ in 0..<N { await ac.inc() }
let d = Double(DispatchTime.now().uptimeNanoseconds - t0)
print("NSLock lock/unlock : \(Int(a / Double(N))) ns per update")
print("serial queue, sync : \(Int(b / Double(N))) ns per update")
print("serial queue, async+drain : \(Int(c / Double(N))) ns per update")
print("actor, await from outside : \(Int(d / Double(N))) ns per update")
}
}
Compiled with swiftc -parse-as-library -O -swift-version 6, one run printed:
NSLock lock/unlock : 3 ns per update
serial queue, sync : 34 ns per update
serial queue, async+drain : 261 ns per update
actor, await from outside : 16988 ns per update
The figures move from run to run and with the number of CPUs given to the container, but their sizes stay apart: the lock at a few nanoseconds, the sync queue at a few tens of nanoseconds, the async block at roughly a hundred to a few hundred nanoseconds (it grows with more CPUs), and the actor call at about a microsecond with one CPU and several to over ten microseconds with eight. The ordering is lock cheapest, then a sync queue hop, then an async block, then an await on an actor, which here includes switching the calling task onto the actor's executor on every call. Treat that ordering as what this setup shows, not a law, because it depends on the platform, the runtime version and the workload. These are illustrative figures for a Linux aarch64 container with Swift 6.0.3, not an iPhone: Apple's runtime and scheduler differ, so measure on a target device with Instruments or XCTest measure before a number drives a decision. What carries over is the shape: a lock is a few instructions, a queue adds an allocation or a wait, and an actor await adds a task switch, which is why an actor suits coarse operations and not one-integer updates in a hot loop.
Actor reentrancy. An actor method that checks, then awaits, then acts is not atomic, because other calls run during the suspension:
import Foundation
// Actor reentrancy: state can change across an await inside an actor method.
actor Account {
var balance = 100
func withdraw(_ amount: Int, label: String) async -> Bool {
guard balance >= amount else { return false } // check
try? await Task.sleep(nanoseconds: 10_000_000) // suspension point: other calls run here
balance -= amount // act, on a stale check
print("\(label) withdrew \(amount), balance now \(balance)")
return true
}
}
let acct = Account()
async let a = acct.withdraw(80, label: "T1")
async let b = acct.withdraw(80, label: "T2")
_ = await (a, b)
print("final balance:", await acct.balance)
Run output:
T1 withdrew 80, balance now 20
T2 withdrew 80, balance now -60
final balance: -60
Timeline: T1 enters withdraw, sees balance = 100 >= 80, and suspends at the await (the 10 ms sleep). The actor is free, so T2 enters, also sees balance = 100 >= 80, and suspends. T1 usually resumes first, after its 10 ms, and subtracts: balance 20. T2 resumes and subtracts from the stale check: balance -60. Which call resumes first is not guaranteed (the two printed lines can swap, with the same final result), but the final balance of -60 does not depend on that order, because both calls already passed the check. async let just starts each call as a child task running concurrently, and await (a, b) collects both. The fix: do the check and the mutation with no await between them, or reserve the funds before suspending.
Actors awaiting each other. Two actors that call each other do not deadlock, because an actor is not held while it is suspended at an await:
import Foundation
actor Ping {
var peer: Pong?
func link(_ p: Pong) { peer = p }
func hit(_ depth: Int) async -> Int {
if depth == 0 { return 0 }
return 1 + (await peer!.hit(depth - 1))
}
}
actor Pong {
var peer: Ping?
func link(_ p: Ping) { peer = p }
func hit(_ depth: Int) async -> Int {
if depth == 0 { return 0 }
return 1 + (await peer!.hit(depth - 1))
}
}
let a = Ping(), b = Pong()
await a.link(b); await b.link(a)
print("levels completed:", await a.hit(10))
Compiled with swiftc -O -swift-version 6 in the same container, it prints levels completed: 10 on every run, including with the container limited to one CPU.
Serial queue self-deadlock.
import Foundation
let q = DispatchQueue(label: "state")
q.sync {
print("outer block running")
q.sync { print("inner block") } // sync onto the queue we are already on
}
print("unreachable")
Run in the same container, the process dies with Signal 5 ... Program crashed: System trap ... __DISPATCH_WAIT_FOR_QUEUE__ in libdispatch.so: libdispatch detects the synchronous call onto its own queue and traps rather than hanging.
Which one to pick, and what flips it
- Call sites are
async, state is a model with several fields: actor. It flips to a lock if profiling shows theawaithop in a hot loop, or if a synchronous API (a delegate, aUITableViewDataSourcemethod) must read the state immediately. - Several writers produce events that must be applied in order: serial queue.
- One shared counter or flag read on the main thread without
await: a lock, with the invariant documented next to it.
Your team owns a large iOS and Android app built on callbacks, GCD and thread pools. How would you migrate it incrementally to structured concurrency (Swift async/await, Kotlin coroutines) without regressions?
Sample Answer
Direct answer
Migrate from the edges inward, one module at a time, behind a safety net, and keep old and new APIs side by side until the numbers prove parity. The order: (0) build the safety net, (1) wrap leaf callback APIs, (2) turn queue-guarded state into actors (Swift) or confined coroutines (Kotlin), (3) switch callers feature by feature with shims for old callers, (4) retire the old paths. Do not rewrite call graphs in a big bang, and do not translate DispatchQueue code line by line, because the semantics differ in four ways listed below.
Terms
Structured concurrency means each task has a parent scope that cancels it and waits for it, so no work is orphaned. In Swift that is async/await, async let, task groups and Task cancellation. In Kotlin it is coroutines with a CoroutineScope and Job. GCD (Grand Central Dispatch) is iOS's queue-based thread pool library. An actor is a Swift type that lets one caller at a time touch its state. A continuation is a handle that lets callback-style code resume a suspended async function: you call resume exactly once, and the Checked variant detects misuse instead of failing silently: a second resume traps and a missing resume logs a warning. A cooperative pool is the small fixed set of threads (about one per CPU core) that runs all async tasks; tasks give the thread back whenever they await, which is why blocking one is harmful.
Phase 0: safety net before any change
- Baseline numbers for each flow you will touch: p50/p95 latency, crash-free rate, hang/ANR rate (an ANR is Android's Application Not Responding dialog; Android's own documentation lists a deadlock between the main thread and another thread, and slow I/O on the main thread, among the common causes).
- Characterisation tests: tests that record what the code does today (ordering, error cases, what happens on cancel), including the odd behaviour, rather than what it should do, so a migration that changes behaviour fails a test. The test in the run below does this for a cache.
- Run Thread Sanitizer on iOS (a compiler-instrumented tool that reports data races as they happen) and StrictMode on Android (a debug-time tool that flags disk or network work on the main thread) in CI. On Swift, turn on stricter compile-time checks gradually:
-strict-concurrency=minimal(checks only code that has already opted in to concurrency annotations), thentargeted(also checks code that usesSendableand actors), thencomplete(checks everything and reports every unsafe crossing of a thread boundary, the same checks Swift 6 mode turns into errors), and only then the Swift 6 language mode. The most useful signal is the warning count atcomplete; getting it to zero is what makes the language-mode switch safe. All three values of the flag were accepted by the Swift 6.0.3 compiler on the Step 1 to 3 program below, which compiled with no diagnostics at each level. - A kill switch per migrated module (a remotely controlled flag that switches back to the old code path), so a regression is a flag flip, not a release.
The four semantic differences that cause regressions
- Ordering. A serial queue runs submitted blocks in order. A
Task { }per event does not guarantee order (before:queue.async { log("A") }; queue.async { log("B") }always logs A then B; after:Task { log("A") }; Task { log("B") }may log B first), and an actor can interleave two calls whenever one of them hits anawait(reentrancy: while call 1 is suspended at anawaitinside the actor, call 2 may run and change the state call 1 read before suspending, so call 1 may resume with a stale assumption such as "the key is not in the cache yet"). For ordered event streams use anAsyncStreamconsumed by one task (Swift) or aChannel/Flowwith one collector (Kotlin). - Blocking. Async code runs on a small cooperative pool, about one thread per CPU core. Blocking one of those threads (
DispatchSemaphore.wait,sync) can starve the pool. The run below shows it: with 14 cores, 13 tasks blocked on a semaphore still let the releasing task run, but 14 blocked tasks did not finish within the 2 second limit (the demo then releases them by hand so the next trial starts clean). With 13 blocked, one thread was still free to run the task that signals the semaphore; with 14, every pool thread was parked waiting for a signal that only a task needing a pool thread could send, so without the manual release they would wait forever. On Android the same rule is the main-thread rule: blocking I/O goes toDispatchers.IOthroughwithContext, andrunBlockingon the main thread invites an ANR. - Lifetime and cancellation. Callback code often kept running after the screen closed. Structured tasks are cancelled with their scope, so side effects you relied on (an analytics event, a final write) may silently stop. Audit each flow: either move the must-run work to a scope that outlives the screen, or make it non-cancellable on purpose. In Kotlin never swallow
CancellationExceptionin a broadcatch. - Which thread delivers the result. Callbacks that were documented to arrive on the main thread must become
@MainActor(Swift) orDispatchers.Main(Kotlin) explicitly. Do not leave it implicit.
Phase 1 to 3 in code
The Swift below was compiled with Swift 6.0.3 in a swift:6.0 Linux container (aarch64), in both the Swift 5 and the Swift 6 language mode, and run. It wraps one callback API with a continuation (a single resume), keeps old callers working through a shim over the new function (via modern: Bool selects whether the shim forwards to the old implementation or to the new async one; as Profile tells the compiler which of the two same-named fetchProfile overloads, callback or async, to call), and replaces a serial-queue-guarded cache by an actor, with a test that both implementations agree after 1,000 concurrent writes.
import Foundation
// ---------- Step 1: wrap one callback API as async, exactly one resume ----------
struct Profile: Sendable, Equatable { let id: Int; let name: String }
/// Legacy API: completion handler, called once, on an arbitrary queue.
func fetchProfile(id: Int, completion: @escaping @Sendable (Result<Profile, Error>) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 0.005) {
id < 0 ? completion(.failure(URLError(.badURL)))
: completion(.success(Profile(id: id, name: "user\(id)")))
}
}
func fetchProfile(id: Int) async throws -> Profile {
try await withCheckedThrowingContinuation { cont in
fetchProfile(id: id) { cont.resume(with: $0) }
}
}
// ---------- Step 2: keep old callers compiling with a shim over the new API ----------
// The legacy API called back on an arbitrary queue, and so does this shim:
// a caller that needs the main thread must hop there itself (see difference 4).
func fetchProfile(id: Int, completion: @escaping @Sendable (Result<Profile, Error>) -> Void,
via modern: Bool) {
guard modern else { return fetchProfile(id: id, completion: completion) }
Task {
do { completion(.success(try await fetchProfile(id: id) as Profile)) }
catch { completion(.failure(error)) }
}
}
// ---------- Step 3: replace a lock/serial-queue guarded cache with an actor ----------
final class QueueCache: @unchecked Sendable { // before
private let queue = DispatchQueue(label: "cache")
private var items: [Int: Profile] = [:]
func put(_ p: Profile) { queue.sync { items[p.id] = p } }
func get(_ id: Int) -> Profile? { queue.sync { items[id] } }
var count: Int { queue.sync { items.count } }
}
actor ActorCache { // after
private var items: [Int: Profile] = [:]
func put(_ p: Profile) { items[p.id] = p }
func get(_ id: Int) -> Profile? { items[id] }
var count: Int { items.count }
}
// ---------- Characterisation test: both versions must behave the same ----------
let old = QueueCache()
let new = ActorCache()
await withTaskGroup(of: Void.self) { g in
for i in 0..<1000 {
g.addTask { let p = Profile(id: i % 100, name: "n\(i % 100)"); old.put(p); await new.put(p) }
}
}
var same = true
for i in 0..<100 { if old.get(i) != (await new.get(i)) { same = false } }
print("caches agree on all 100 keys:", same, "| counts:", old.count, await new.count)
// Wrapper behaves like the original, for success and for failure.
print("async success:", try await fetchProfile(id: 7))
do { _ = try await fetchProfile(id: -1) as Profile } catch { print("async failure:", (error as? URLError)?.code == .badURL) }
let viaShim: Profile = try await withCheckedThrowingContinuation { cont in
fetchProfile(id: 3, completion: { cont.resume(with: $0) }, via: true)
}
print("shim over async:", viaShim)
It printed:
caches agree on all 100 keys: true | counts: 100 100
async success: Profile(id: 7, name: "user7")
async failure: true
shim over async: Profile(id: 3, name: "user3")
The blocking-starvation check for item 2 above, compiled and run the same way:
import Foundation
let cores = ProcessInfo.processInfo.activeProcessorCount
print("cores:", cores)
/// `blocked` tasks each park their thread on a semaphore; one more task would release them all.
/// Returns true if everything finished within 2 seconds.
func finishesInTime(blocked: Int) -> Bool {
let gate = DispatchSemaphore(value: 0)
let done = DispatchSemaphore(value: 0)
Task {
await withTaskGroup(of: Void.self) { group in
for _ in 0..<blocked { group.addTask { gate.wait() } } // blocks a cooperative thread
group.addTask { for _ in 0..<blocked { gate.signal() } } // needs a free thread to run
}
done.signal()
}
let ok = done.wait(timeout: .now() + 2) == .success
if !ok { for _ in 0..<blocked { gate.signal() } } // release them so the next trial starts clean
return ok
}
print("blocked tasks = cores - 1, finished in 2 s:", finishesInTime(blocked: max(cores - 1, 1)))
print("blocked tasks = cores, finished in 2 s:", finishesInTime(blocked: cores))
It printed, in a container with 14 cores:
cores: 14
blocked tasks = cores - 1, finished in 2 s: true
blocked tasks = cores, finished in 2 s: false
Pool size depends on how many CPUs the process can actually use, but the rule holds on any of them: never block inside async code. The cores - 1 threshold above holds only where the reported core count matches the pool width. In a container restricted to a subset of CPUs (a CPU affinity mask), activeProcessorCount still reported 14 while the pool was evidently narrower, and then even cores - 1 blocked tasks did not finish. Size such an experiment from the CPUs the process may run on, not from the reported count.
On Android, the equivalent first step:
// Same idea as the Swift wrapper: one callback API, one suspend function.
suspend fun fetchProfile(id: Int): Profile = suspendCancellableCoroutine { cont -> // suspends the coroutine until cont is resumed
val call = legacyClient.fetch(id, object : Callback {
override fun onSuccess(p: Profile) { cont.resume(p) }
override fun onError(e: Throwable) { cont.resumeWithException(e) }
})
cont.invokeOnCancellation { call.cancel() } // runs if the coroutine is cancelled before the callback fires: cancel the legacy call too
}
class ProfileViewModel(private val io: CoroutineDispatcher = Dispatchers.IO) : ViewModel() {
fun load(id: Int) = viewModelScope.launch { // cancelled when the ViewModel is cleared
val p = withContext(io) { repository.blockingLoad(id) } // blocking work stays on IO
_state.value = UiState.Loaded(p)
}
}
Android's coroutine guidance says to inject dispatchers rather than hardcode them (so tests can replace them), to make suspend functions safe to call from the main thread by moving blocking work with withContext, to start coroutines in the ViewModel, and to avoid GlobalScope.
Rollout order and gates
Pick the module with the least shared state and the best test coverage first (a networking leaf, not the sync engine). Ship it dark behind the flag, ramp 1%, 10%, 50%, 100%, comparing the Phase 0 metrics at each step, and hold a stage until the new path is no worse on crash-free rate and hang/ANR rate. Migrate the two platforms in step so behaviour (cancel, retry, ordering) stays consistent for users who use both. Check the minimum OS version your Xcode and Swift versions support for async/await against your deployment target; below it, keep the callback API as the public surface.
What would change the plan: if the app has a large, well-tested serial-queue core that is not a source of bugs, leave it and only wrap it. Migrate what hurts (leaks, races, callback pyramids), not everything.
Describe a situation where you found a subtle race condition or concurrency bug in a multi-threaded or async project. Explain how you reproduced the issue, debugging tools or logging you used, the root cause (ordering, shared state), and the fix you implemented. How did you ensure the fix covered all relevant code paths?
Sample Answer
Situation
I worked on an async checkout service (Python asyncio, where one event loop per process is the scheduler that runs many tasks on a single thread, switching between them whenever one waits) that reserved units of limited-stock items during sales. After one sale, the nightly reconciliation job (a batch job that compares what the orders say was sold with what the warehouse says was in stock) reported more units sold than we had in stock for a few items. There were no exceptions, no failed requests and no alerts: the bug produced wrong data, not crashes. My task was to find out why and make sure it could not recur.
What I did
1. Turned a vague symptom into a testable claim. The reconciliation numbers said "sometimes oversold", so I wrote down the invariant that must always hold: units sold plus units left equals starting stock, and units left never goes below zero. Everything after that was about breaking that invariant on demand.
2. Read the code for a read-await-write shape. asyncio code switches tasks only at an await, so a race (a result that depends on the timing of tasks or threads) needs an await between a read and the write that depends on it. I searched the reservation path for that and found it: the code checked inventory > 0, then awaited the card authorization (a slow external call), then decremented. Every request that arrived while an earlier one was waiting on the card saw the old stock and passed the check. Single-threaded does not mean race-free; it means races can only happen at await points.
3. Reproduced it in a harness before touching the code. I wrote a script that fires 100 buyers, spread over 20 ms, at 10 units of stock, and checks the invariant over 20 trials. asyncio.sleep is how a task waits without blocking the loop, and asyncio.gather starts many tasks together and collects their results:
import asyncio, random
STOCK, BUYERS = 10, 100
async def charge_card(fail_rate, rng):
await asyncio.sleep(rng.uniform(0.001, 0.005)) # the slow payment call
return rng.random() >= fail_rate
# BROKEN: the check and the decrement are separated by an await.
async def reserve_broken(inv, sku, fail_rate, rng):
if inv[sku] > 0: # check
if not await charge_card(fail_rate, rng): # other requests run here
return False
inv[sku] -= 1 # act, on a stale check
return True
return False
# FIXED: claim the unit synchronously, then await, and give it back on failure.
async def reserve_fixed(inv, sku, fail_rate, rng):
if inv[sku] <= 0:
return False
inv[sku] -= 1 # no await between check and decrement
if await charge_card(fail_rate, rng):
return True
inv[sku] += 1 # compensate if the payment failed
return False
async def trial(reserve, seed, fail_rate):
rng = random.Random(seed)
inv = {"sku-1": STOCK}
async def buyer():
await asyncio.sleep(rng.uniform(0, 0.02)) # requests arrive spread over 20 ms
return await reserve(inv, "sku-1", fail_rate, rng)
results = await asyncio.gather(*(buyer() for _ in range(BUYERS)))
sold = sum(results)
return sold, inv["sku-1"]
async def main():
for name, fn in (("broken", reserve_broken), ("fixed", reserve_fixed)):
oversold = []
invariant_ok = 0
for seed in range(20):
sold, left = await trial(fn, seed, fail_rate=0.0)
oversold.append(max(0, sold - STOCK))
invariant_ok += (sold + left == STOCK and left >= 0)
print(f"{name:6} no failures: sold {STOCK + min(oversold)}..{STOCK + max(oversold)} units of {STOCK} in stock, "
f"invariant held in {invariant_ok}/20 trials")
ok = 0
for seed in range(20):
sold, left = await trial(reserve_fixed, seed, fail_rate=0.3)
ok += (sold + left == STOCK and left >= 0)
print(f"fixed 30% card failures: sold + left == {STOCK} and left >= 0 in {ok}/20 trials")
asyncio.run(main())
Run in a python:3.12-slim container (Python 3.12), the broken line always reports the invariant held in 0 of 20 trials and the other two lines are always 20 of 20, while the oversold range in the broken line differs from run to run (the best trial usually sells in the low 20s and the worst usually in the high 30s to low 40s). One sample run:
broken no failures: sold 22..41 units of 10 in stock, invariant held in 0/20 trials
fixed no failures: sold 10..10 units of 10 in stock, invariant held in 20/20 trials
fixed 30% card failures: sold + left == 10 and left >= 0 in 20/20 trials
How to read the first line: each trial counts units sold, and the script prints STOCK + oversold for the best and worst of the 20 trials. sold 22..41 units of 10 in stock therefore means the luckiest trial sold 22 units against 10 in stock (12 too many) and the unluckiest sold 41 (31 too many). The old code never kept the invariant in any trial across repeated runs, while the fixed version sold exactly 10 every time and kept it throughout, including with 30 percent injected card failures. The exact oversold figures change from run to run, which is what a race looks like; the invariant check, not the figures, is the assertion.
One broken interleaving with real numbers (times are illustrative): stock is 10. Buyer 1 arrives at 0.0 ms, sees inv > 0 (10), and starts waiting on the card, which takes 1 to 5 ms. About 5 buyers arrive per millisecond (100 over 20 ms), so buyers 2, 3, 4 and the rest arrive while buyer 1 is still waiting, and every one of them also sees 10, because nobody has decremented yet. Only when buyer 1's card call returns at, say, 3 ms does stock become 9. By then roughly 15 buyers have passed the check against a stock of 10, and the same thing repeats as each later buyer arrives before the earlier decrements land. That is how 100 buyers sell several times the stock.
4. Fixed it by removing the gap, not by adding a lock around the slow call. The fix claims the unit synchronously (check and decrement with no await between them), then awaits the card, and gives the unit back if the payment fails. A lock around the whole reserve would also be correct, but it would serialize every card call for that item and make a flash sale queue behind one slow authorization. The compensation step (undoing the earlier claim when a later step fails, here putting the unit back) is what the 30 percent failure trial exercises: a failed payment must not leak a unit.
5. Checked that the fix covered every path. Three things, none of which was "I looked at it again":
- I grepped the codebase for every other place that read a shared counter, awaited, then wrote it (cart limits and coupon redemption had the same shape) and fixed or ticketed each.
- I added the invariant as an assertion in the reservation code in staging, so any future path that breaks it fails loudly instead of showing up in a nightly report.
- I kept the harness as a regression test in CI, and made it fail on the old code first, to prove the test could actually catch the bug.
The in-process fix only protects one event loop. With several worker processes the same race exists between processes, so the durable version is a conditional database update, UPDATE inventory SET stock = stock - 1 WHERE sku = ? AND stock > 0, followed by a check of the rows-affected count (how many rows the statement changed: 1 means this buyer got a unit, 0 means the stock > 0 condition failed and the item is sold out). The database applies the check and the decrement as one atomic step, so no other process can slip in between them. Run in the same python:3.12-slim container with SQLite (a stand-in for the production database) on 2 units and 3 buyers:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE inventory (sku TEXT PRIMARY KEY, stock INTEGER)")
db.execute("INSERT INTO inventory VALUES ('sku-1', 2)")
for buyer in (1, 2, 3):
cur = db.execute("UPDATE inventory SET stock = stock - 1 WHERE sku = ? AND stock > 0", ("sku-1",))
print(f"buyer {buyer}: rows affected = {cur.rowcount}", "reserved" if cur.rowcount == 1 else "sold out")
print("stock left:", db.execute("SELECT stock FROM inventory").fetchone()[0])
buyer 1: rows affected = 1 reserved
buyer 2: rows affected = 1 reserved
buyer 3: rows affected = 0 sold out
stock left: 0
I treated that as the follow-up for the multi-process deployment.
Result
The harness went from 0 of 20 invariant-holding trials on the old code (in every run) to 20 of 20 on the fix, including the injected-failure case. In production, the measure I tracked was the reconciliation report: it had flagged mismatches after every sale before the change and showed none on the sales that followed.
What I would do differently
I would have written the invariant check and the reconciliation alert before the first sale rather than after it, and I would have reviewed the code for "await between check and write" the day we adopted asyncio, because that review costs minutes and the oversell cost a sale.
Shape to reuse for your own story
Name the invariant that was broken, the exact tool or log that exposed the ordering (here a harness; for threads it might be ThreadSanitizer, a compiler-supported tool that reports unsynchronised access to shared memory, jstack, which prints every Java thread's stack so you can see who is waiting on what, or request-id-tagged logs), the root cause in one sentence (an ordering and shared state, not "a timing issue"), the fix and the alternative you rejected, and the measurement that shows it held. Replace the production figures with your real ones.
Unlock Full Question Bank
Get access to all 38 Language-Level Concurrency and Multithreading interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.