chunrong918
V2EX  ›  问与答

Java :什么场合不适合用 violate

  •  
  •   chunrong918 · Apr 11, 2019 · 2952 views
    This topic created in 2771 days ago, the information mentioned may be changed or developed.

    如题,请教一下

    12 replies  •  2019-04-12 15:25:07 +08:00
    alan0liang
    alan0liang
    Apr 11, 2019 via Android
    1
    volatile 吧
    Luckyray
    Luckyray
    Apr 11, 2019
    2
    提问方式不咋地
    yidinghe
    yidinghe
    PRO
    Apr 11, 2019❤️1
    3
    默认情况下不适用 volatile。
    zjp
    zjp
    Apr 11, 2019
    4
    拼写错的时候...
    这个在 《 Java 并发编程实战》写得很清楚了
    You can use volatile variables only when all the following criteria are met:
    • Writes to the variable do not depend on its current value, or you can ensure
    that only a single thread ever updates the value;
    • The variable does not participate in invariants with other state variables;
    and
    • Locking is not required for any other reason while the variable is being
    accessed.
    letianqiu
    letianqiu
    Apr 11, 2019❤️1
    5
    volatile 只能保证 visibility,但是不能保证 atomicity。所以典型的 scenario 是一个共享的变量,只有一个 thread 会更新这个变量,其他 thread 都是只读取不更新。
    http://tutorials.jenkov.com/java-concurrency/volatile.html
    Lonely
    Lonely
    Apr 11, 2019
    6
    答案:不告诉你
    macfred
    macfred
    Apr 12, 2019 via Android
    8
    @letianqiu happens before order
    Finest
    Finest
    Apr 12, 2019
    9
    并发计数的场景就不适用,因为不是原子操作。
    jswh
    jswh
    Apr 12, 2019
    10
    前几天刚刚研究过 volatile

    http://www.jswh.me/?p=163

    Volatile 的原意是挥发性的,不稳定。而 Volatile variable 指的是那些可能通过多种途径进行修改的数据。比如上面的 VGA text buffer,如果在程序中使用那么指针对应的数据,除了程序本身会修改,其他的程序也会修改,显卡驱动( bios?)也会修改。

    这样的数据会有一个问题,就是很多时候对于单一程序只会进行读取 /写入这种操作中的一种,比如 VGA text buffer 读取很多时候是显卡的事,程序则只负责写入。这样的数据,编译器会认为是没有意义的,很可能会在优化的时候被去掉,反而出现错误。所以一些语言中会把这样的数据标记出来。比如 c、c++、java 都有关键字 volatile。MMIO 是 volatile 最常用的场景之一。

    所以我觉得只适用于那些无法控制的数据。
    xiaoidea
    xiaoidea
    Apr 12, 2019
    11
    你应该问什么场合下使用 volatile,因为除了少数适用场合外,其他一律不要用 volatile
    chunrong918
    chunrong918
    OP
    Apr 12, 2019
    12
    @alan0liang 哈哈 写错了
    @xiaoidea 嗯嗯

    @jswh 赞
    @hand515 标准答案了

    @letianqiu 是的
    @yidinghe 这么答也没错

    @Luckyray 欢迎指正
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3373 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 10:10 · PVG 18:10 · LAX 02:10 · JFK 05:10
    ♥ Do have faith in what you're doing.