Why volatile Is Not Thread‑Safe: A Java Increment Test
The article presents a Java program where 100 threads each increment a volatile int 1,000 times, showing that the final value may be less than the expected 100,000, and explains that volatile only guarantees visibility, not atomicity, making it unsuitable for concurrent modifications.
This article demonstrates that the volatile keyword in Java does not provide thread‑safety for compound operations such as incrementing a shared counter.
public class VolatileTest {
private static volatile int k = 0;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
public void run() {
for (int j = 0; j < 1000; j++) {
k++;
}
}
}).start();
}
System.out.println(k);
}
}Characteristics
The volatile modifier only guarantees that a thread reads the latest value from main memory; it does not make compound actions like k++ atomic.
Applicable Scenario
Suitable when a single thread performs writes while multiple threads only read the variable.
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.
ZhiKe AI
We dissect AI-era technologies, tools, and trends with a hardcore perspective. Focused on large models, agents, MCP, function calling, and hands‑on AI development. No fluff, no hype—only actionable insights, source code, and practical ideas. Get a daily dose of intelligence to simplify tech and make efficiency tangible.
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.
