美文网首页
[Java 多线程] volatile关键字实现的简单读写锁

[Java 多线程] volatile关键字实现的简单读写锁

作者: oyealex | 来源:发表于2017-01-05 14:47 被阅读0次

2017-1-5 14:46:58 oye
Example Code:

public class CheesyCounter {
    // Employs the cheap read-write lock trick
    // All mutative operations MUST be done with the 'this' lock held
    @GuardedBy("this")
    private volatile int value;

    public int getValue() { return value; }

    public synchronized int increment() {
        return value++;
    }
}

Analysis:

  • 使用 volatile 关键字修饰变量,保证获取到的变量值是最新的
  • 对写方法使用 synchronized 同步,保证写入操作时安全的
  • volatilesynchronized 轻量
  • 适用于有大量读操作,较少写操作的情况,例如需要经常检查某一指标、变量的情况(温度监控等)

相关文章

网友评论

      本文标题:[Java 多线程] volatile关键字实现的简单读写锁

      本文链接:https://www.haomeiwen.com/subject/wwdzvttx.html