Synchronized和Volatile底层知识、内存屏障相关内容

基本(早前写的):https://blog.csdn.net/qq_31482599/article/details/88564206

Synchronized

 注:不同虚拟机对于锁的实现机制都不同,本文主要是针对hotspot的实现进行简单学习

java 对于synchronized的使用主要有两方式

  • synchronized 修饰方法
     可以查看修饰方法这种情况对应的字节码,通过字节码可以看到这种情况是通过对该方法添加了一个访问标识符 Access flags 是 synchronized 的标识控制锁的。即JVM通过该访问标识符开实现同步功能的。
    在这里插入图片描述

  • synchronized 用于代码块
    同步代码块字节码截图:在这里插入图片描述
    通过字节码,可以看到 synchronized 代码块是通过两条指令 monitorenter 和 monitorexit 指令实现代码同步功能的。

    对于monitor,通过在网上查找资料,大概概括如下:
     我们可以把它理解为一个同步工具,也可以描述为一种同步机制,它通常被描述为一个对象。
     与一切皆对象一样,所有的Java对象是天生的Monitor,每一个Java对象都有成为Monitor的潜质,因为在Java的设计中 ,每一个Java对象自打娘胎里出来就带了一把看不见的锁,它叫做内部锁或者Monitor锁。Monitor 是线程私有的数据结构,每一个被锁住的对象都会和一个monitor关联(对象头的MarkWord中的LockWord指向monitor的起始地址),同时monitor中有一个Owner字段存放拥有该锁的线程的唯一标识,表示该锁被这个线程占用。

    JVM 中对于 这两条指令monitorenter 和monitorexit的介绍
    monitorenter
    Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
    If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
    If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
    If another thread already owns the monitor associated with objectref, the thread blocks until the monitor’s entry count is zero, then tries again to gain ownership.
    monitorexit
    The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

    大致意思如下:

    执行monitorenter指令时,就会获取对应的monitor,每一个monitor都维护一个数字,monitor

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值