2013年3月8日星期五

volatile

From Evernote:

volatile

Clipped from: file:///

正确使用 volatile 变量的条件

您只能在有限的一些情形下使用 volatile 变量替代锁。要使 volatile 变量提供理想的线程安全,必须同时满足下面两个条件:

  • 对变量的写操作不依赖于当前值。
  • 该变量没有包含在具有其他变量的不等式中。

对于应用场景而言, 

@NotThreadSafe   public class NumberRange {      private int lower, upper;        public int getLower() { return lower; }      public int getUpper() { return upper; }        public void setLower(int value) {           if (value > upper) //不等式              throw new IllegalArgumentException(...);          lower = value;      }        public void setUpper(int value) {           if (value < lower)               throw new IllegalArgumentException(...);          upper = value;      }  }  


作为独立标记使用:


一次性发布:
独立观察:
volatile bean 模式

无可奈何的写锁

没有评论: