Java synchronized 包含两方面的含义
互斥
JVM 通过对象锁来实现互斥:
协作是通过 Object wait, notify/notifyAll 方法实现的。
对应到JVM 的底层术语,这一机制叫做 monitor:
在不同区域的 Thread 对应的状态(Java Thread 的状态图):
在底层的JVM 或许会有更多的状态,但是,暴露在 Java Thread 的状态是在 java.lang.Thread 中定义的,注意 JDK 6 修订了 interrupt 的语义。
互斥
JVM 通过对象锁来实现互斥:
typedef struct object {
uintptr_t lock;
Class *class;
} Object
协作
协作是通过 Object wait, notify/notifyAll 方法实现的。
对应到JVM 的底层术语,这一机制叫做 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:
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;
}
}