Understanding Thread Safety: From ThreadLocal to Locks and CAS
This article explains why thread safety concerns memory rather than threads, compares stack‑local and heap‑shared data, introduces ThreadLocal for per‑thread isolation, and covers mutual‑exclusion locks, optimistic CAS, and their appropriate use cases in concurrent programming.
What "thread safety" really means
Thread safety does not refer to the safety of a thread itself but to the safety of the memory it accesses. In modern multitasking operating systems each process has its own private memory, while all threads of a process share a common heap area. If data in the heap can be accessed by multiple threads without protection, it can be unintentionally modified.
Private data lives on the stack
Each thread receives its own stack memory, which only that thread can read or write. Local variables such as double sum = 0; and int count = scores.length; are allocated on the stack, so different threads get independent copies of these variables.
Shared data in the heap and ThreadLocal
When a variable must be visible to multiple methods, it becomes a field of a class and is stored in the shared heap. To keep such data safe while still allowing each thread its own view, Java provides ThreadLocal. A ThreadLocal instance stores a separate copy of a value for each thread, effectively copying the heap data N times and letting each thread operate on its own copy.
class StudentAssistant {
ThreadLocal<String> realName = new ThreadLocal<>();
ThreadLocal<Double> totalScore = new ThreadLocal<>();
String determineDegree() {
double score = totalScore.get();
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "E";
}
}Each thread accesses its own realName and totalScore values via ThreadLocal.get(), so modifications by one thread never affect another.
Read‑only data (constants) are inherently safe
Data placed in the heap that is never modified—such as final double PASS_SCORE = 60; —is also thread‑safe because no thread can change it.
class StudentAssistant {
final double PASS_SCORE = 60;
}Mutual‑exclusion locks for shared mutable data
When multiple threads must modify the same heap variable, a lock must guard the critical section. A thread obtains the lock before updating the data and releases it afterward, ensuring only one thread can change the value at a time.
class ClassAssistant {
double totalScore = 60;
final Lock lock = new Lock();
void addScore(double s) {
lock.obtain();
totalScore += s;
lock.release();
}
void subScore(double s) {
lock.obtain();
totalScore -= s;
lock.release();
}
}CAS (Compare‑And‑Swap) and optimistic locking
Locks incur overhead, especially when contention is low. In such cases, Compare‑And‑Swap (CAS) offers an optimistic alternative: a thread reads the current value, performs its computation, and attempts to write the new value only if the original value has not changed. If another thread modified the value in the meantime, the CAS fails and the operation is retried.
CAS works well when the probability of concurrent modification is small; otherwise, repeated retries become more expensive than a simple lock.
Summary of strategies
Isolate data by keeping it in thread‑local stack memory.
Use ThreadLocal to give each thread its own copy of heap data.
Mark data as immutable (constants) to make it inherently safe.
Apply mutual‑exclusion locks for shared mutable state.
Prefer CAS/optimistic locking when contention is low.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
dbaplus Community
Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
