synchronized的底层JVM实现机制

来源:互联网 发布:拟态网络 编辑:程序博客网 时间:2024/06/05 16:59
Java synchronized 包含两方面的含义

互斥
JVM 通过对象锁来实现互斥:
[cpp] view plain copy
print?在CODE上查看代码片派生到我的代码片
  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:
[cpp] view plain copy
print?在CODE上查看代码片派生到我的代码片
  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:

[cpp] view plain copy
print?在CODE上查看代码片派生到我的代码片
  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;}}


0 0
原创粉丝点击