Java Memory Model

The Java Memory Model defines how threads interact through memory.

All source code is available at github.

Computer Memory Model

sh-4.2# lscpu | grep 'CPU(s)\|cache'

CPU(s):                2
On-line CPU(s) list:   0,1
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K

sh-4.2# cat /proc/meminfo | grep MemTotal

MemTotal:        2047036 kB
Computer Memory Model.png
  • 2 threads(1 thread per cpu) may run concurrently.
  • Data is read from RAM to Cache, then processed by CPU, then written(flushed) to the RAM.
  • The CPU Optimizer determines when to flush.
  • Data in the Cache is NOT visible to other threads.
  • Data in the RAM is visible to all threads, threads can communicate through RAM.

JMM goals

JMM need to ensure visibility, ordering and atomicity regardless of the underlying hardware memory model.
A basic understanding of java concurrent stress test(JCST) is required.
You can check the sample code from github.

Visibility

Write by one thread to a shared object may be invisible to another thread because of the existence cache.

Code

  • Thread actor1 keeps reading from shared object (v).
  • Thread actor1 exits while v = 1 (changes from Thread signal is visible).
  • Thread signal is started after Thread actor1.
  • Thread signal write(v = 1) to shared object.
@Outcome(id = "TERMINATED", expect = Expect.ACCEPTABLE, desc = "write in signal is visible to actor1.")
@Outcome(id = "STALE", expect = Expect.ACCEPTABLE_INTERESTING, desc = "write in signal is NOT visible to actor1.")
public class VisibilityTest {

    @JCStressTest(Mode.Termination)
    @JCStressMeta(VisibilityTest.class)
    @State
    public static class PlainReadWrite {
        int v;

        @Actor
        public void actor1() {
            while (v == 0) {
                // spin
            }
        }

        @Signal
        public void signal() {
            v = 1;
        }
    }

    @JCStressTest(Mode.Termination)
    @JCStressMeta(VisibilityTest.class)
    @State
    public static class VolatileReadWrite {
        volatile int v;

        @Actor
        public void actor1() {
            while (v == 0) {
                // spin
            }
        }

        @Signal
        public void signal() {
            v = 1;
        }
    }

    @JCStressTest(Mode.Termination)
    @JCStressMeta(VisibilityTest.class)
    @State
    public static class SynchronizedReadWrite {
        int v;

        @Actor
        public void actor1() {
            while (v == 0) {
                synchronized (this) {
                    if (v == 0) {
                        continue;//release lock
                    }
                }
            }
        }

        @Signal
        public void signal() {
            synchronized (this) {
                v = 1;
            }
        }
    }
}

Result

  • JCST TERMINATED state means write in Thread signal is visible to Thread actor1.
  • JCST STALE state means write in Thread signal is NOT visible to Thread actor1.
visibility test result.png

Conclusion

  1. PlainReadWrite
    • Visibility of plain access is NOT ensured.
  2. VolatileReadWrite
    • volatile ensures visibility of shared object.
  3. SynchronizedReadWrite
    • synchronized ensures visibility of shared object.

Ordering

  1. The compiler is free to reorder certain instructions as an optimization when it would not change the semantics of the program.
  2. The processor is allowed to execute operations out of order under some circumstances.
  3. The cache is generally allowed to write variables back to main memory in a different order than they were written by the program.

Code

  • Thread actor1 write to i = 1; iSet = true;.
  • Thread actor2 read from r.r1 = iSet; r.r2 = i;.
@Outcome(id = "false, 0", expect = ACCEPTABLE, desc = "actor2 reads before actor1.")
@Outcome(id = "true, 1", expect = ACCEPTABLE, desc = "actor2 reads after actor1.")
@Outcome(id = "false, 1", expect = ACCEPTABLE, desc = "actor1 write i, actor2 read iSet, actor2 read i, actor1 write iSet")
@Outcome(id = "true, 0", expect = ACCEPTABLE_INTERESTING, desc = "REORDERING, actor1 write iSet, actor2 read iSet, actor2 read i, actor1 write i")
public class OrderingTest {

    @JCStressTest
    @JCStressMeta(OrderingTest.class)
    @State
    public static class PlainOrdering {
        int i;
        boolean iSet;

        @Actor
        public void actor1() {
            i = 1;
            iSet = true;
        }

        @Actor
        public void actor2(ZI_Result r) {
            r.r1 = iSet;
            r.r2 = i;
        }
    }

    @JCStressTest
    @JCStressMeta(OrderingTest.class)
    @State
    public static class VolatileOrdering {
        int i;
        volatile boolean iSet;

        @Actor
        public void actor1() {
            i = 1;
            iSet = true;
        }

        @Actor
        public void actor2(ZI_Result r) {
            r.r1 = iSet;
            r.r2 = i;
        }
    }

    @JCStressTest
    @JCStressMeta(OrderingTest.class)
    @State
    public static class SynchronizedOrdering {
        int i;
        boolean iSet;

        @Actor
        public void actor1() {
            synchronized (this) {
                i = 1;
                iSet = true;
            }
        }

        @Actor
        public void actor2(ZI_Result r) {
            synchronized (this) {
                r.r1 = iSet;
                r.r2 = i;
            }
        }
    }
}

Result

Execution Order.png
  • JCST (false, 0) state, read write is executed as case 1.
  • JCST (false, 1) state, read write is executed as case 2.
  • JCST (true, 0) state, read write is executed as case 4/5(reordering observed).
  • JCST (true, 1) state, read write is executed as case 3.
visibility test result.png

Conclusion

  1. PlainOrdering
    • Ordering of plain write and read is NOT ensured.
  2. VolatileOrdering
    • volatile ensures ordering of write and read.
  3. SynchronizedOrdering
    • synchronized ensures ordering of write and read.

Atomicity

An operation is atomic,
A set of operations is atomic,

Code

public class AtomicityTest {

    @JCStressTest
    @Outcome(id = "0", expect = Expect.ACCEPTABLE, desc = "See initial value while writer not finished.")
    @Outcome(id = "-1", expect = Expect.ACCEPTABLE, desc = "See full value while writer finished")
    @Outcome(expect = Expect.FORBIDDEN, desc = "partial values are forbidden.")
    @State
    public static class IntegerAtomicity {
        int v;

        @Actor
        public void writer() {
            v = 0xFFFFFFFF;
        }


        @Actor
        public void reader(I_Result r) {
            r.r1 = v;

        }
    }

    @JCStressTest
    @Outcome(id = "0", expect = Expect.ACCEPTABLE, desc = "See initial value while writer not finished.")
    @Outcome(id = "65535", expect = Expect.ACCEPTABLE, desc = "See full value while writer0 finished.")
    @Outcome(id = "-65536", expect = Expect.ACCEPTABLE, desc = "See full value while writer1 finished.")
    @Outcome(expect = Expect.FORBIDDEN, desc = "Partial values are forbidden even in case of concurrent update.")
    @State
    public static class IntegerConcurrentAtomicity {
        int v;

        @Actor
        public void writer0() {
            v = 0x0000FFFF;
        }

        @Actor
        public void writer1() {
            v = 0xFFFF0000;
        }


        @Actor
        public void reader(I_Result r) {
            r.r1 = v;

        }
    }

    @JCStressTest
    @Outcome(id = "0", expect = Expect.ACCEPTABLE, desc = "See initial value while writer not finished.")
    @Outcome(id = "-1", expect = Expect.ACCEPTABLE, desc = "See full value while writer finished.")
    @Outcome(expect = Expect.ACCEPTABLE_INTERESTING, desc = "Partial values violate access atomicity, but allowed under JLS.")
    @State
    public static class LongAtomicity {
        long v;

        @Actor
        public void writer() {
            v = 0xFFFFFFFF_FFFFFFFFL;
        }

        @Actor
        public void reader(J_Result r) {
            r.r1 = v;
        }
    }

    @JCStressTest
    @Outcome(id = "0", expect = Expect.ACCEPTABLE, desc = "See initial value while writer not finished.")
    @Outcome(id = "-1", expect = Expect.ACCEPTABLE, desc = "See full value while writer finished.")
    @Outcome(expect = Expect.FORBIDDEN, desc = "Partial values are forbidden.")
    @State
    public static class VolatileLongAtomicity {
        volatile long v;

        @Actor
        public void writer() {
            v = 0xFFFFFFFF_FFFFFFFFL;
        }

        @Actor
        public void reader(J_Result r) {
            r.r1 = v;
        }
    }


    @JCStressTest
    @Outcome(id = "1", expect = Expect.ACCEPTABLE_INTERESTING, desc = "One update lost.")
    @Outcome(id = "2", expect = Expect.ACCEPTABLE, desc = "Both updates.")
    @State
    public static class PlainIncrement {
        int v;

        @Actor
        public void actor1() {
            v++;
        }

        @Actor
        public void actor2() {
            v++;
        }

        @Arbiter
        public void arbiter(I_Result r) {
            r.r1 = v;
        }
    }


    @JCStressTest
    @Outcome(id = "1", expect = Expect.ACCEPTABLE_INTERESTING, desc = "One update lost.")
    @Outcome(id = "2", expect = Expect.ACCEPTABLE, desc = "Both updates.")
    @State
    public static class VolatileIncrement {
        volatile int v;

        @Actor
        public void actor1() {
            v++;
        }

        @Actor
        public void actor2() {
            v++;
        }

        @Arbiter
        public void arbiter(I_Result r) {
            r.r1 = v;
        }
    }

    @JCStressTest
    @Outcome(id = "1", expect = Expect.FORBIDDEN, desc = "One update lost.")
    @Outcome(id = "2", expect = Expect.ACCEPTABLE, desc = "Both updates.")
    @State
    public static class SynchronizedIncrement {
        int v;

        @Actor
        public void actor1() {
            synchronized (this) {
                v++;
            }
        }

        @Actor
        public void actor2() {
            synchronized (this) {
                v++;
            }
        }

        @Arbiter
        public void arbiter(I_Result r) {
            r.r1 = v;
        }
    }

    @JCStressTest
    @Outcome(id = "1", expect = Expect.ACCEPTABLE_INTERESTING, desc = "One update lost.")
    @Outcome(id = "2", expect = Expect.ACCEPTABLE, desc = "Both updates.")
    @State
    public static class AtomicIntegerIncrement {
        AtomicInteger v = new AtomicInteger();

        @Actor
        public void actor1() {
            v.getAndIncrement();
        }

        @Actor
        public void actor2() {
            v.getAndIncrement();
        }

        @Arbiter
        public void arbiter(I_Result r) {
            r.r1 = v.get();
        }
    }

    @JCStressTest
    @Outcome(id = "100, 0", expect = Expect.ACCEPTABLE, desc = "Transfer not start yet.")
    @Outcome(id = "0, 100", expect = Expect.ACCEPTABLE, desc = "Transfer completed.")
    @Outcome(id = "0, 0", expect = Expect.ACCEPTABLE_INTERESTING, desc = "See partial result.")
    @Outcome(id = "100, 100", expect = Expect.ACCEPTABLE_INTERESTING, desc = "See partial result.")
    @State
    public static class PlainTransfer {
        int a = 100;
        int b;

        @Actor
        public void actor1() {
            a = a - 100;
            b = b + 100;
        }

        @Actor
        public void arbiter(II_Result r) {
            r.r1 = a;
            r.r2 = b;
        }
    }

    @JCStressTest
    @Outcome(id = "100, 0", expect = Expect.ACCEPTABLE, desc = "Transfer not start yet.")
    @Outcome(id = "0, 100", expect = Expect.ACCEPTABLE, desc = "Transfer completed.")
    @Outcome(expect = Expect.FORBIDDEN, desc = "Forbidden case.")
    @State
    public static class SynchronizedTransfer {
        int a = 100;
        int b;

        @Actor
        public void actor1() {
            synchronized (this) {
                a = a - 100;
                b = b + 100;
            }
        }

        @Actor
        public void arbiter(II_Result r) {
            synchronized (this) {
                r.r1 = a;
                r.r2 = b;
            }
        }
    }
}

Result

  • Integer Atomicity
Integer Atomicity.png
  • Long Atomicity
Long Atomicity.png
  • Increment Atomicity
Increment Atomicity.png
  • Transfer Atomicity
Transfer Atomicity.png

Conclusion

  • Read/Write of primitive types (boolean, byte, char, short, int, float, double, long) is atomic.
    Concurrent update of primitive types is safe.

  • Read/Write of long/double in 32 bits machine is not atomic.
    R/W to long/double can be divided into R/W high 32bits and low 32bits.
    volatile long/double ensures atomicity jls.

  • Increment(i++) is not atomic.
    i++ can be divided to (load i, i+1, store i).
    volatile doesn't ensure atomicity.
    java.util.concurrent.atomic.AtomicInteger ensures atomicity.
    synchronized ensures atomicity.

  • Transfer $100 from A to B is not atomic.
    This can be divided to (A-100, B+100).
    synchronized (A-100, B+100) ensures atomicity.

Memory Barrier

Types of memory barrier

Memory Barrier.png

JSR-133 ordering rules

JSR-133 ordering rules.png
  • Volatile Load can't be reordered with subsequent operations.
  • Monitor Enter can't be reordered with subsequent operations.
  • Volatile Store can't be reordered with precedent operations.
  • Monitor Exit can't be reordered with precedent operations.
  • Volatile Store can't be reordered with subsequent Volatile Load and Monitor Enter.
  • Monitor Exit can't be reordered with subsequent Volatile Load and Monitor Enter.

volatile

volatile memory barrier.png

synchronized

synchronized memory barrier.png

final

final memory barrier.png

Reference

Wiki java memory model
The Java Memory Model by Doug Lea
JLS-17
JSR-133
Fixing the Java Memory Model, Part 1
Fixing the Java Memory Model, Part 2
tutorials jenkov java-memory-model
深入理解Java内存模型

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,384评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,845评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,148评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,640评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,731评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,712评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,703评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,473评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,915评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,227评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,384评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,063评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,706评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,302评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,531评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,321评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,248评论 2 352