synchronized的底层JVM实现机制

本文深入解析Java中的synchronized关键字,探讨其实现互斥和协作的基本原理。通过对JVM底层机制的剖析,介绍了对象锁及monitor机制,并展示了Thread状态转换的具体过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java synchronized 包含两方面的含义

互斥
JVM 通过对象锁来实现互斥:
  1. typedef struct object {  
  2. uintptr_t lock;  
  3. Class *class;  
  4. } Object  
typedef struct object {
uintptr_t lock;
Class *class;
} Object
协作
协作是通过 Object wait, notify/notifyAll 方法实现的。

对应到JVM 的底层术语,这一机制叫做 monitor:
  1. typedef struct monitor {  
  2. pthread_mutex_t lock;  
  3. Thread *owner;  
  4. Object *obj;  
  5. int count;  
  6. int in_wait;  
  7. uintptr_t entering;  
  8. int wait_count;  
  9. Thread *wait_set;  
  10. struct monitor *next;  
  11. } Monitor;  
typedef struct monitor {
pthread_mutex_t lock;
Thread *owner;
Object *obj;
int count;
int in_wait;
uintptr_t entering;
int wait_count;
Thread *wait_set;
struct monitor *next;
} Monitor;


在不同区域的 Thread 对应的状态(Java Thread 的状态图):

在底层的JVM 或许会有更多的状态,但是,暴露在 Java Thread 的状态是在 java.lang.Thread 中定义的,注意 JDK 6 修订了 interrupt 的语义。

比如,在底层,进行获取 lock 动作到获得 lock 之间有一小段状态叫做 BLOCKED:

  1. void monitorLock(Monitor *mon, Thread *self) {  
  2. if(mon->owner == self)  
  3. mon->count++;  
  4. else {  
  5. if(pthread_mutex_trylock(&mon->lock)) {  
  6. disableSuspend(self);  
  7.   
  8. self->blocked_mon = mon;  
  9. self->blocked_count++;  
  10. self->state = BLOCKED;  
  11.   
  12. pthread_mutex_lock(&mon->lock);  
  13.   
  14. self->state = RUNNING;  
  15. self->blocked_mon = NULL;  
  16.   
  17. enableSuspend(self);  
  18. }  
  19. mon->owner = self;  
  20. }  
  21. }  
void monitorLock(Monitor *mon, Thread *self) {
if(mon->owner == self)
mon->count++;
else {
if(pthread_mutex_trylock(&mon->lock)) {
disableSuspend(self);

self->blocked_mon = mon;
self->blocked_count++;
self->state = BLOCKED;

pthread_mutex_lock(&mon->lock);

self->state = RUNNING;
self->blocked_mon = NULL;

enableSuspend(self);
}
mon->owner = self;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值