Fundamentals 2 min read

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.

ZhiKe AI
ZhiKe AI
ZhiKe AI
Why volatile Is Not Thread‑Safe: A Java Increment Test

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaConcurrencythread safetyvolatileatomicityvisibility
ZhiKe AI
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.