Concurrency Safety, Deadlocks, and Array vs Linked List Tradeoffs
Data Structure DesignModel answerLast updated
Four short fundamentals questions: what makes code safe under concurrent use, what a deadlock is, how to handle deadlocks, and how contiguous arrays compare with pointer-based linked lists.
Imagine a quick oral round on core software engineering concepts. You get four short questions back to back. Answer each one precisely and briefly, the way you would say it aloud, and add a small concrete example wherever it sharpens the answer.
You may state your assumptions up front (for instance, language-neutral versus a specific language such as Java, threads in one process versus distributed locks, and how deep to go).
Question 1: Safe concurrent use. What does it mean for code to be thread-safe? What properties make a class or function safe to call from several threads at once, and what are the main techniques for achieving it?
Question 2: Deadlock. Define a deadlock. Give a minimal example, list the conditions that must all hold for one to occur, and explain how it differs from livelock and starvation.
Question 3: Dealing with deadlocks. What strategies exist for handling deadlocks? Cover prevention, avoidance, and detection with recovery, and mention practical habits for keeping them out of production code and for diagnosing one that has happened.
Question 4: Arrays versus linked lists. Compare the two in terms of memory layout, the cost of common operations (index access, search, insertion and deletion at the ends and in the middle, append on a growable array), cache behavior, and per-element overhead. Say when you would pick each one.
A strong answer uses exact definitions, shows a concrete example for each idea, names the cost of each remedy rather than just the remedy, and shows practical judgment.
Hints
Hint 1
For Q1, start from the failure: shared mutable state plus unsynchronized access gives lost updates (two threads doing count++). Then list the fixes (confinement, immutability, locks, atomics, concurrent collections) and what each costs.
Hint 2
For Q2 and Q3, tie everything to the four necessary conditions (mutual exclusion, hold and wait, no preemption, circular wait). Each prevention technique works by breaking exactly one of them.
Hint 3
For Q4, separate the asymptotic story from the hardware story: a linked list's O(1) insertion assumes you already hold the node, and finding it costs O(n) with poor cache locality, so arrays usually win in practice.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Q1: Thread safety
Definition. Code is thread-safe if it keeps behaving correctly, meeting its specification and preserving its invariants, when several threads use it at the same time, without callers adding their own external synchronization. The result must not depend on how the scheduler interleaves threads.
What it rules out.
- Race conditions on shared mutable state. Example: two threads run
count++on a shared counter. Each does read, add, write, so both can read 5 and both write 6, losing an update. - Broken invariants. A structure whose fields must change together (say, a
sizefield and an internal array) can be observed half-updated. - Visibility and ordering problems. Without a happens-before relationship, a thread may see a stale value, or see writes reordered by the compiler or CPU.
Ways to achieve it, with costs.
- Avoid sharing (confinement). Thread-local data, or message passing between threads. No contention, but it needs design discipline and copying.
- Immutability. Objects that never change after construction are safe to share freely. The cost is allocating new objects on each change.
- Mutual exclusion (locks,
synchronized, mutexes). Simple and correct when done carefully, but it serializes access, risks contention, and introduces deadlock risk. - Atomics and lock-free techniques (compare-and-swap). Good for single-variable updates such as counters. Hard to compose across several variables and prone to subtle bugs (ABA).
- Concurrent collections (concurrent hash maps, blocking queues). Well-tested building blocks, but compound actions such as check-then-put still need atomic methods like
putIfAbsent.
Common mistake: assuming that making each method individually safe makes a sequence of calls safe. A "check if absent, then insert" over a synchronized map is still a race.
Q2: Deadlock
Definition. A set of threads is deadlocked when each is blocked waiting for a resource held by another thread in the set, so none can ever proceed.
Minimal example. Thread A locks L1 then wants L2. Thread B locks L2 then wants L1. If each gets its first lock, both wait forever.
Coffman conditions (all four must hold).
- Mutual exclusion: resources are held exclusively.
- Hold and wait: a thread holds one resource while waiting for another.
- No preemption: resources cannot be forcibly taken away.
- Circular wait: a cycle of threads each waiting on the next.
Related problems.
- Livelock: threads are active but make no progress, for example two threads that keep backing off and retrying in lockstep. The state changes, but nothing gets done.
- Starvation: one thread is perpetually denied a resource (for example by unfair scheduling or priority) while the system as a whole still progresses.
Q3: Handling deadlocks
Prevention: break one condition.
- Break circular wait with a global lock order. Always acquire locks in the same order (for example by account ID when transferring between two accounts). This is the most practical technique. Cost: you must know all locks up front and enforce the convention.
- Break hold and wait. Acquire everything at once, or release what you hold before waiting. Cost: lower concurrency and possible over-locking.
- Break no-preemption with timed attempts. Use
tryLock(timeout); if it fails, release held locks, back off (with randomized delay to avoid livelock) and retry. Cost: retry logic and possible wasted work. - Break mutual exclusion where feasible, for example with immutable or lock-free structures.
Avoidance. The system grants a request only if the resulting state is "safe" (the banker's algorithm). It requires knowing maximum resource needs in advance, so it is rarely used in application code.
Detection and recovery. Build a wait-for graph and look for cycles. Databases do this: they detect a cycle, pick a victim (often the cheapest transaction to roll back), abort it, and let the application retry. Cost: wasted work and the need for idempotent retry logic.
Engineering habits.
- Hold locks for the shortest time, and never call unknown or callback code while holding a lock.
- Prefer fewer, coarser locks, or higher-level constructs (concurrent collections, queues, actors).
- Document lock ordering; use lock-ordering checkers or static analysis.
- Always use timeouts on lock acquisition in production services.
Diagnosis. Take a thread dump (for example jstack, or a debugger attached to the process). Look for threads in a blocked state and the locks each holds and awaits; many runtimes print the detected cycle directly. Then fix the ordering.
Q4: Arrays versus linked lists
Memory layout. An array is one contiguous block, with element i at base + i * size. A linked list is separately allocated nodes, each holding a value and one or two pointers.
| Operation | Array | Singly linked list |
|---|---|---|
| Access by index | O(1) | O(n) |
| Search (unsorted) | O(n) | O(n) |
| Insert/delete at front | O(n) (shift) | O(1) |
| Append at end | Amortized O(1) on a growable array (occasional O(n) resize) | O(1) with a tail pointer |
| Insert/delete in middle | O(n) (shift) | O(1) once you hold the node, but O(n) to find it |
| Delete at tail | O(1) | O(n) singly, O(1) doubly with a tail pointer |
Cache locality. Arrays are scanned sequentially, which suits CPU caches and prefetching. Linked nodes are scattered on the heap, so traversal causes cache misses. This is why arrays often beat lists even for workloads where the asymptotics seem to favor lists, such as moderate numbers of middle insertions.
Memory overhead. A list pays one or two pointers per element plus allocator overhead. A growable array may waste unused capacity (often up to about 2x in the worst case just after a resize) but has no per-element overhead.
When to choose which.
- Array (or dynamic array): default choice. Random access, iteration, binary search on sorted data, compact storage, and mostly appends.
- Linked list: frequent insertion or removal at known positions (for example splicing, LRU cache with a hash map pointing at nodes), stack or queue behavior where you cannot tolerate resize spikes, and situations where element addresses must remain stable.
Common mistakes: claiming list insertion is "O(1)" without noting the search cost, and ignoring cache effects. A strong answer says: use an array by default, and reach for a linked list when you already hold node references and need constant-time splicing.