Skip to main content

java notify

背景

java 的waitnotify是一对Object上面的api,这个api需要对对象做synchronized

wait notify 需要对对象获取synchronized 锁住对象,否则需要

// -----------------------------------------------------------------------------
// Wait/Notify/NotifyAll
//
// Note: a subset of changes to ObjectMonitor::wait()
// will need to be replicated in complete_exit
void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
JavaThread* current = THREAD;

assert(InitDone, "Unexpectedly not initialized");

CHECK_OWNER(); // Throws IMSE if not owner. ///////////////////////////////////////////////// 这里会判断是否有synchronized 加上同步块

EventJavaMonitorWait event;


...
}

CHECK_OWNER 宏展开: 会调研 ObjectMonitor::check_owner


// Checks that the current THREAD owns this monitor and causes an
// immediate return if it doesn't. We don't use the CHECK macro
// because we want the IMSE to be the only exception that is thrown
// from the call site when false is returned. Any other pending
// exception is ignored.
#define CHECK_OWNER() \
do { \
if (!check_owner(THREAD)) { \
assert(HAS_PENDING_EXCEPTION, "expected a pending IMSE here."); \
return; \
} \
} while (false)

然后我们看ObjectMonitor::check_owner 实现:


// Returns true if the specified thread owns the ObjectMonitor.
// Otherwise returns false and throws IllegalMonitorStateException
// (IMSE). If there is a pending exception and the specified thread
// is not the owner, that exception will be replaced by the IMSE.
bool ObjectMonitor::check_owner(TRAPS) {
JavaThread* current = THREAD;
void* cur = owner_raw();
assert(cur != anon_owner_ptr(), "no anon owner here");
if (cur == current) {
return true;
}
if (LockingMode != LM_LIGHTWEIGHT && current->is_lock_owned((address)cur)) {
set_owner_from_BasicLock(cur, current); // Convert from BasicLock* to Thread*.
_recursions = 0;
return true;
}
THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
"current thread is not owner", false);
}

最后看ObjectMonitor::owner_raw 实现

inline void* ObjectMonitor::owner_raw() const {
return Atomic::load(&_owner);
}

ObjectMonitor 就算monitor的实现了:

class ObjectMonitor : public CHeapObj<mtObjectMonitor> {
...
private:
static void* anon_owner_ptr() { return reinterpret_cast<void*>(ANONYMOUS_OWNER); }

void* volatile _owner; // pointer to owning thread OR BasicLock
volatile uint64_t _previous_owner_tid; // thread id of the previous owner of the monitor
...
};