Does Java volatile variables impose a happens-before relationship before it is read?

后端 未结 1 801
臣服心动
臣服心动 2021-01-02 13:18

I have a piece of code which looks like this:

Snippet A:

class Creature {
    private static long numCreated;
    public Creature() {
             


        
相关标签:
1条回答
  • 2021-01-02 13:47

    See http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility:

    A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.

    So the answer is yes. The write of the volatile in the constructor happens before the read of the volatile in numCreated(). And since the non-atomic incrementation is still done in a synchronized block, the synchronization is alright (the incrementation is not atomic, but the write of the volatile long is).

    0 讨论(0)
提交回复
热议问题