java의 volatile

java core 2017. 4. 17. 10:08

java의 volatile 타입은 다음과 같이 정의되어 있다. volatile Fields

The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

소스에서 자바의 volatile을 잘 만날 수 없는 요인 중에 하나는 자바 concurrent package의 클래스가 자바의 volatile을 감싸고 있기 때문이다. 

예를 들어  AtomicInteger의 내부를 살펴본다. value 값에 대해서 volatile라고 선언되어 있다.


52 public class AtomicInteger extends Number implements {

53     private static final long serialVersionUID = 6214790243416807050L;


55     // setup to use Unsafe.compareAndSwapInt for updates

56     private static final Unsafe unsafe = Unsafe.getUnsafe();

57     private static final long valueOffset;


59     static {

60       try {

61         valueOffset = unsafe.objectFieldOffset

62             (AtomicInteger.class.getDeclaredField("value"));

63       } catch (Exception ex) { throw new Error(ex); }

64     }


66     private volatile int value;



73     public More ...AtomicInteger(int initialValue) {

74         value = initialValue;

75     }

Posted by 김용환 '김용환'

댓글을 달아 주세요