目錄
What Is the volatile Keyword?
When to Use volatile
What Is the synchronized Keyword?
Example: Using synchronized
How synchronized Ensures Visibility
Key Differences: volatile vs synchronized
Common Pitfalls and Best Practices
Example: Why volatile Isn't Enough for count
Alternatives: AtomicInteger , ReentrantLock , etc.
Summary
首頁 Java java教程 Java中的線程安全:'揮發性”和'同步”指南

Java中的線程安全:'揮發性”和'同步”指南

Jul 30, 2025 am 02:43 AM

volatile和synchronized在Java中都解決線程安全問題,但作用不同:1. volatile保證變量的可見性,確保多線程下讀寫直接與主內存交互,適用於狀態標誌等單次讀寫場景,但不提供原子性;2. synchronized提供原子性和可見性,通過互斥鎖確保同一時間只有一個線程執行代碼塊,適用於復合操作如count ;3. volatile不能替代synchronized,對於非原子操作仍需synchronized或使用AtomicInteger等並發工具類,正確選擇工具可確保線程安全且高效。

Thread Safety in Java: A Guide to `volatile` and `synchronized`

In Java, thread safety is critical when multiple threads access shared data. Without proper synchronization, programs can exhibit unpredictable behavior due to race conditions, visibility issues, and inconsistent state. Two key tools for managing thread safety are volatile and synchronized . While both help with concurrency, they serve different purposes and are not interchangeable.

Thread Safety in Java: A Guide to `volatile` and `synchronized`

Let's break down how each works, when to use them, and what problems they solve.


What Is the volatile Keyword?

The volatile keyword ensures visibility of changes to variables across threads. When a variable is declared volatile , it tells the JVM:

Thread Safety in Java: A Guide to `volatile` and `synchronized`
  • Writes to this variable are immediately flushed to main memory.
  • Reads of this variable always come from main memory, not from a thread's local cache.

This prevents threads from using stale cached values — a common issue in multi-threaded environments.

Example: Using volatile

 public class VolatileExample {
    private volatile boolean running = true;

    public void stop() {
        running = false;
    }

    public void run() {
        while (running) {
            // do work
        }
        System.out.println("Stopped");
    }
}

In this example, one thread calls run() and another calls stop() . Without volatile , the run() thread might never see the updated value of running because it could be cached in CPU memory. With volatile , the change is guaranteed to be visible.

Thread Safety in Java: A Guide to `volatile` and `synchronized`

When to Use volatile

Use volatile when:

  • The variable is read and written by multiple threads.
  • The variable does not depend on its previous value (ie, no compound operations like count ).
  • You only need visibility , not atomicity.

❌ Don't use volatile for operations like x — they are not atomic even if the variable is volatile.


What Is the synchronized Keyword?

synchronized provides both mutual exclusion (only one thread can execute the block/method at a time) and visibility (changes made inside the synchronized block are visible to other threads).

It can be applied to:

  • Instance methods (locks on the instance)
  • Static methods (locks on the class object)
  • Code blocks (with a specified lock object)

Example: Using synchronized

 public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count ; // atomic operation due to synchronization
    }

    public synchronized int getCount() {
        return count;
    }
}

Here, synchronized ensures that only one thread can execute increment() or getCount() at a time, preventing race conditions on count .

How synchronized Ensures Visibility

When a thread enters a synchronized block, it acquires the monitor lock and:

  • Flushes its local cache.
  • Reloads variables from main memory.

When it exits, it writes changes back to main memory. So, like volatile , it guarantees visibility — but with added atomicity.


Key Differences: volatile vs synchronized

Feature volatile synchronized
Atomicity No (only for single read/write) Yes (entire block/method)
Visibility Yes Yes
Mutual Exclusion No Yes
Performance Lightweight Heavier (monitor locking)
Applicable to Variables only Methods and code blocks

Common Pitfalls and Best Practices

  • ✅ Use volatile for state flags (eg, shutdownRequested , initialized ).
  • ✅ Use synchronized when you need atomicity (eg, incrementing, updating multiple variables).
  • ❌ Don't assume volatile makes compound operations safe.
  • ❌ Avoid overusing synchronized — it can cause contention and reduce performance.

Example: Why volatile Isn't Enough for count

 public class BadCounter {
    private volatile int count = 0;

    public void increment() {
        count ; // Not atomic: read, increment, write
    }
}

Even though count is volatile , count involves three steps. Two threads could read the same value, leading to lost updates. You need synchronized or AtomicInteger .


Alternatives: AtomicInteger , ReentrantLock , etc.

For better performance and flexibility, consider:

  • AtomicInteger , AtomicLong , etc. — provide atomic operations without blocking.
  • java.util.concurrent.locks.ReentrantLock — more control than synchronized .

Example with AtomicInteger :

 private AtomicInteger count = new AtomicInteger(0);

public void increment() {
    count.incrementAndGet(); // thread-safe and efficient
}

Summary

  • Use volatile for simple shared flags where you need visibility but not atomicity.
  • Use synchronized when you need both atomicity and visibility , especially for compound operations.
  • Understand that volatile doesn't replace synchronized — they solve different parts of the concurrency puzzle.

Thread safety isn't just about preventing crashes — it's about ensuring correctness under concurrent access. Choosing the right tool ( volatile , synchronized , or atomic classes) makes your code both safe and efficient.

以上是Java中的線程安全:'揮發性”和'同步”指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1511
276
Java虛擬線程性能基準測試 Java虛擬線程性能基準測試 Jul 21, 2025 am 03:17 AM

虚拟线程在高并发、IO密集型场景下性能优势显著,但需注意测试方法与适用场景。1.正确测试应模拟真实业务尤其是IO阻塞场景,使用JMH或Gatling等工具对比平台线程;2.吞吐量差距明显,在10万并发请求下可高出几倍至十几倍,因其更轻量、调度高效;3.测试中需避免盲目追求高并发数,适配非阻塞IO模型,并关注延迟、GC等监控指标;4.实际应用中适用于Web后端、异步任务处理及大量并发IO场景,而CPU密集型任务仍适合平台线程或ForkJoinPool。

如何在Windows中設置Java_home環境變量 如何在Windows中設置Java_home環境變量 Jul 18, 2025 am 04:05 AM

tosetjava_homeonwindows,firstLocateThejDkinStallationPath(例如,C:\ programFiles \ java \ jdk-17),tencreateasyemystemenvironmentvaria blenamedjava_homewiththatpath.next,updateThepathvariaby byadding%java \ _home%\ bin,andverifyTheSetupusingjava-versionAndjavac-v

如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

要正確處理JDBC事務,必須先關閉自動提交模式,再執行多個操作,最後根據結果提交或回滾;1.調用conn.setAutoCommit(false)以開始事務;2.執行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調用conn.commit(),若發生異常則調用conn.rollback()確保數據一致性;同時應使用try-with-resources管理資源,妥善處理異常並關閉連接,避免連接洩漏;此外建議使用連接池、設置保存點實現部分回滾,並保持事務盡可能短以提升性能。

在Java中實現鏈接列表 在Java中實現鏈接列表 Jul 20, 2025 am 03:31 AM

實現鍊錶的關鍵在於定義節點類並實現基本操作。 ①首先創建Node類,包含數據和指向下一個節點的引用;②接著創建LinkedList類,實現插入、刪除和打印功能;③append方法用於在尾部添加節點;④printList方法用於輸出鍊錶內容;⑤deleteWithValue方法用於刪除指定值的節點,處理頭節點和中間節點的不同情況。

Java微服務服務網格集成 Java微服務服務網格集成 Jul 21, 2025 am 03:16 AM

ServiceMesh是Java微服務架構演進的必然選擇,其核心在於解耦網絡邏輯與業務代碼。 1.ServiceMesh通過Sidecar代理處理負載均衡、熔斷、監控等功能,使開發聚焦業務;2.Istio Envoy適合中大型項目,Linkerd更輕量適合小規模試水;3.Java微服務應關閉Feign、Ribbon等組件,交由Istiod管理服務發現與通信;4.部署時確保Sidecar自動注入,注意流量規則配置、協議兼容性、日誌追踪體系建設,並採用漸進式遷移和前置化監控規劃。

高級Java收集框架優化 高級Java收集框架優化 Jul 20, 2025 am 03:48 AM

为提升Java集合框架性能,可从以下四点优化:1.根据场景选择合适类型,如频繁随机访问用ArrayList、快速查找用HashSet、并发环境用ConcurrentHashMap;2.初始化时合理设置容量和负载因子以减少扩容开销,但避免内存浪费;3.使用不可变集合(如List.of())提高安全性与性能,适用于常量或只读数据;4.防止内存泄漏,使用弱引用或专业缓存库管理长期存活的集合。这些细节显著影响程序稳定性与效率。

比較Java框架:Spring Boot vs Quarkus vs Micronaut 比較Java框架:Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

前形式攝取,quarkusandmicronautleaddueTocile timeProcessingandGraalvSupport,withquarkusoftenpernperforminglightbetterine nosserless notelless centarios.2。

用雅加達EE在Java建立靜止的API 用雅加達EE在Java建立靜止的API Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

See all articles