V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
chunrong918
V2EX  ›  问与答

Java :什么场合不适合用 violate

  •  
  •   chunrong918 · 2019-04-11 21:54:38 +08:00 · 1751 次点击
    这是一个创建于 1834 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题,请教一下

    12 条回复    2019-04-12 15:25:07 +08:00
    alan0liang
        1
    alan0liang  
       2019-04-11 22:12:36 +08:00 via Android
    volatile 吧
    Luckyray
        2
    Luckyray  
       2019-04-11 22:12:41 +08:00
    提问方式不咋地
    yidinghe
        3
    yidinghe  
       2019-04-11 22:15:09 +08:00   ❤️ 1
    默认情况下不适用 volatile。
    zjp
        4
    zjp  
       2019-04-11 22:18:45 +08:00
    拼写错的时候...
    这个在 《 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
        5
    letianqiu  
       2019-04-11 22:23:18 +08:00   ❤️ 1
    volatile 只能保证 visibility,但是不能保证 atomicity。所以典型的 scenario 是一个共享的变量,只有一个 thread 会更新这个变量,其他 thread 都是只读取不更新。
    http://tutorials.jenkov.com/java-concurrency/volatile.html
    Lonely
        6
    Lonely  
       2019-04-11 23:08:03 +08:00
    答案:不告诉你
    troywinter
        7
    troywinter  
       2019-04-11 23:40:52 +08:00
    macfred
        8
    macfred  
       2019-04-12 03:24:21 +08:00 via Android
    @letianqiu happens before order
    hand515
        9
    hand515  
       2019-04-12 09:17:52 +08:00
    并发计数的场景就不适用,因为不是原子操作。
    jswh
        10
    jswh  
       2019-04-12 09:31:23 +08:00
    前几天刚刚研究过 volatile

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

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

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

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

    @jswh
    @hand515 标准答案了

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

    @Luckyray 欢迎指正
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1347 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:32 · PVG 01:32 · LAX 10:32 · JFK 13:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.