The Wayback Machine - https://web.archive.org/web/20200701001449/https://github.com/Snailclimb/JavaGuide/issues/649
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

老哥可能对synchronized底层原理有误解或者不清楚java对象的内存布局 #649

Open
guang19 opened this issue Feb 21, 2020 · 4 comments
Labels

Comments

@guang19
Copy link
Contributor

@guang19 guang19 commented Feb 21, 2020

image

上面描述基本没啥问题,但是 : “线程试图获取锁也就是获取 monitor(monitor对象存在于每个Java对象的对象头中” 这句话很容易给人误解。在java内存中由对象头,实例数据和对齐填充三部分组成,当然对齐填充可能不固定。

对象头可以分为2部分数据组成. (如果是数组,对象头还会保存数组长度)
下面是openjdk8 的hotspot源码:

对象头组成

具体的可以参照我写的: https://github.com/guang19/framework-learning/blob/dev/jdk-jvm-juc/Jdk&Jvm&Juc.md

然后关于老哥在对于synchronized的优化中的这些描述:
image

首先偏向锁和轻量级锁的目的是不一样的,偏向锁应该适用于单线程无锁竞争环境而轻量级适用于多线程无锁竞争环境(多线程轮流执行)。

然后这句描述 : “轻量级锁在无竞争的情况下使用 CAS 操作去代替使用互斥量。而偏向锁在无竞争的情况下会把整个同步都消除掉。”

个人觉得这句话描述不明,让人以为只有轻量级锁使用了CAS。实际上只要看过cpp源码就知道,整个synchronized的实现本身就是基于CAS的 ,轻量级锁和偏向锁都是使用了CAS操作的,偏向锁是使用CAS修改java锁对象的对象头的markword的偏向线程ID,而轻量级锁是使用CAS修改整个MarkWord为指向线程栈帧的指针。。
这个也可参考我上面的那个链接。

其它的地方建议老哥改的具体一点,虽然您写的确实让人比较好懂,但还是有地方让人较为疑惑。。

@Snailclimb
Copy link
Owner

@Snailclimb Snailclimb commented Feb 26, 2020

我还是没太搞太清楚,有时间再好好研究下。

@zhangguijian
Copy link

@zhangguijian zhangguijian commented Mar 6, 2020

老哥,太强了,解惑了。

@ClownQiang
Copy link

@ClownQiang ClownQiang commented Apr 6, 2020

活到老,学到老,老哥太强了

@hokage123
Copy link

@hokage123 hokage123 commented Jun 10, 2020

Synchronized is a keyword it means that if any method has that than only it would check for lock or monitor otherwise not.
There also comes a Concept of synchronized class in which all method are synchronized.
Also a concept of synchronized block comes if you want three four line to be acessed in synchronized manner and other having quick access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
5 participants
You can’t perform that action at this time.