美文网首页
Java内存模型&happens-before规则

Java内存模型&happens-before规则

作者: 大风过岗 | 来源:发表于2020-09-10 11:30 被阅读0次

Java 内存模型

java-memory-model-fefe.png

由上图可知,在此内存模型下,线程的工作空间local memory 和主内存是独立的,由于每个线程都是在自己的工作空间中运行,如果出现线程A修改了变量a的值,但没有及时写回到主内存的话。后续的线程b从主内存中读取到的变量a的值就仍旧是一个老值(stale value)。由此带来了线程安全性问题。

happens-before

happens-before是JMM(Java Memory Model)为保证线程安全性,而提供的一种排序规则。JVM遵循此规则以实现原子性和内存可见性,从而保证线程安全性。

happens-before规则

  • 1 、 Each action in a thread happens-before every action in that thread that comes later in the program order
    即: 在单个线程中,语句的编程顺序就是他们的执行顺序。

  • 2、An unlock on a monitor happens-before every subsequent lock on that same monitor
    解锁操作要位于后续的加锁操作之前。

    没解锁,说明某个线程还没有执行完临界区的代码,所以后续的加锁请求
    亦即:后续的进入临界区的请求,是不能被允许的。

  • 3、A write to a volatile field happens-before every subsequent read of that same volatile

    对volatile变量的写入操作要位于后续的读取该volatile变量的请求之前。这样做的目的,就保证了volatile的内存可见性,一旦volatile类型的变量的写入操作完成,就立马把它写入到主内存中。这样就保证了后续的读取操作,就一定会读取到最新的写入值。

  • 4、A call to Thread.start() on a thread happens-before any actions in the started thread
    Thread.start()调用位于已启动线程的任何操作之前执行。

  • 5、All actions in a thread happen-before any other thread successfully returns from a Thread.join() on that thread
    传递性:如果 A happens- before B,且 B happens- before C,那么 A happens- before C

相关文章

网友评论

      本文标题:Java内存模型&happens-before规则

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