`
lobin
  • 浏览: 425854 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JVM lock/unlock

 
阅读更多

 

SharkRuntime::monitorenter

 

JRT_ENTRY(void, SharkRuntime::monitorenter(JavaThread*      thread,
                                           BasicObjectLock* lock))
  if (PrintBiasedLockingStatistics)
    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());

  Handle object(thread, lock->obj());
  assert(Universe::heap()->is_in_reserved_or_null(object()), "should be");
  if (UseBiasedLocking) {
    // Retry fast entry if bias is revoked to avoid unnecessary inflation
    ObjectSynchronizer::fast_enter(object, lock->lock(), true, CHECK);
  } else {
    ObjectSynchronizer::slow_enter(object, lock->lock(), CHECK);
  }
  assert(Universe::heap()->is_in_reserved_or_null(lock->obj()), "should be");
JRT_END
SharkRuntime::monitorexit

 

 

JRT_ENTRY(void, SharkRuntime::monitorexit(JavaThread*      thread,
                                          BasicObjectLock* lock))
  Handle object(thread, lock->obj());
  assert(Universe::heap()->is_in_reserved_or_null(object()), "should be");
  if (lock == NULL || object()->is_unlocked()) {
    THROW(vmSymbols::java_lang_IllegalMonitorStateException());
  }
  ObjectSynchronizer::slow_exit(object(), lock->lock(), thread);
JRT_END
 

 

SharedRuntime::complete_monitor_locking_C

 

JRT_ENTRY_NO_ASYNC(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread))
  oop obj(_obj);
#ifndef PRODUCT
  _monitor_enter_ctr++;             // monitor enter slow
#endif
  if (PrintBiasedLockingStatistics) {
    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
  }
  Handle h_obj(THREAD, obj);
  if (UseBiasedLocking) {
    // Retry fast entry if bias is revoked to avoid unnecessary inflation
    ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
  } else {
    ObjectSynchronizer::slow_enter(h_obj, lock, CHECK);
  }
  assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
JRT_END
 

 

Deoptimization::relock_objects

 

// relock objects for which synchronization was eliminated
void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread) {
  for (int i = 0; i < monitors->length(); i++) {
    MonitorInfo* mon_info = monitors->at(i);
    if (mon_info->eliminated()) {
      assert(mon_info->owner() != NULL, "reallocation was missed");
      Handle obj = Handle(mon_info->owner());
      markOop mark = obj->mark();
      if (UseBiasedLocking && mark->has_bias_pattern()) {
        // New allocated objects may have the mark set to anonymously biased.
        // Also the deoptimized method may called methods with synchronization
        // where the thread-local object is bias locked to the current thread.
        assert(mark->is_biased_anonymously() ||
               mark->biased_locker() == thread, "should be locked to current thread");
        // Reset mark word to unbiased prototype.
        markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
        obj->set_mark(unbiased_prototype);
      }
      BasicLock* lock = mon_info->lock();
      ObjectSynchronizer::slow_enter(obj, lock, thread);
    }
    assert(mon_info->owner()->is_locked(), "object must be locked now");
  }
}

 

InterpreterRuntime::monitorenter

 

//%note monitor_1
IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
#ifdef ASSERT
  thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
  if (PrintBiasedLockingStatistics) {
    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
  }
  Handle h_obj(thread, elem->obj());
  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
         "must be NULL or an object");
  if (UseBiasedLocking) {
    // Retry fast entry if bias is revoked to avoid unnecessary inflation
    ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
  } else {
    ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
  }
  assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
         "must be NULL or an object");
#ifdef ASSERT
  thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
IRT_END
 
InterpreterRuntime::monitorexit
//%note monitor_1
IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
#ifdef ASSERT
  thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
  Handle h_obj(thread, elem->obj());
  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
         "must be NULL or an object");
  if (elem == NULL || h_obj()->is_unlocked()) {
    THROW(vmSymbols::java_lang_IllegalMonitorStateException());
  }
  ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
  // Free entry. This must be done here, since a pending exception might be installed on
  // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
  elem->set_obj(NULL);
#ifdef ASSERT
  thread->last_frame().interpreter_frame_verify_monitor(elem);
#endif
IRT_END
 
Runtime1::monitorenter

 

JRT_ENTRY_NO_ASYNC(void, Runtime1::monitorenter(JavaThread* thread, oopDesc* obj, BasicObjectLock* lock))
  NOT_PRODUCT(_monitorenter_slowcase_cnt++;)
  if (PrintBiasedLockingStatistics) {
    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
  }
  Handle h_obj(thread, obj);
  assert(h_obj()->is_oop(), "must be NULL or an object");
  if (UseBiasedLocking) {
    // Retry fast entry if bias is revoked to avoid unnecessary inflation
    ObjectSynchronizer::fast_enter(h_obj, lock->lock(), true, CHECK);
  } else {
    if (UseFastLocking) {
      // When using fast locking, the compiled code has already tried the fast case
      assert(obj == lock->obj(), "must match");
      ObjectSynchronizer::slow_enter(h_obj, lock->lock(), THREAD);
    } else {
      lock->set_obj(obj);
      ObjectSynchronizer::fast_enter(h_obj, lock->lock(), false, THREAD);
    }
  }
JRT_END

Runtime1::monitorexit

JRT_LEAF(void, Runtime1::monitorexit(JavaThread* thread, BasicObjectLock* lock))
  NOT_PRODUCT(_monitorexit_slowcase_cnt++;)
  assert(thread == JavaThread::current(), "threads must correspond");
  assert(thread->last_Java_sp(), "last_Java_sp must be set");
  // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
  EXCEPTION_MARK;

  oop obj = lock->obj();
  assert(obj->is_oop(), "must be NULL or an object");
  if (UseFastLocking) {
    // When using fast locking, the compiled code has already tried the fast case
    ObjectSynchronizer::slow_exit(obj, lock->lock(), THREAD);
  } else {
    ObjectSynchronizer::fast_exit(obj, lock->lock(), THREAD);
  }
JRT_END

 

 

 

void Monitor::lock (Thread * Self) {
#ifdef CHECK_UNHANDLED_OOPS
  // Clear unhandled oops so we get a crash right away.  Only clear for non-vm
  // or GC threads.
  if (Self->is_Java_thread()) {
    Self->clear_unhandled_oops();
  }
#endif // CHECK_UNHANDLED_OOPS
 
  debug_only(check_prelock_state(Self));
  assert (_owner != Self              , "invariant") ;
  assert (_OnDeck != Self->_MutexEvent, "invariant") ;
 
  if (TryFast()) {
 Exeunt:
    assert (ILocked(), "invariant") ;
    assert (owner() == NULL, "invariant");
    set_owner (Self);
    return ;
  }
 
  // The lock is contended ...
 
  bool can_sneak = Self->is_VM_thread() && SafepointSynchronize::is_at_safepoint();
  if (can_sneak && _owner == NULL) {
    // a java thread has locked the lock but has not entered the
    // critical region -- let's just pretend we've locked the lock
    // and go on.  we note this with _snuck so we can also
    // pretend to unlock when the time comes.
    _snuck = true;
    goto Exeunt ;
  }
 
  // Try a brief spin to avoid passing thru thread state transition ...
  if (TrySpin (Self)) goto Exeunt ;
 
  check_block_state(Self);
  if (Self->is_Java_thread()) {
    // Horribile dictu - we suffer through a state transition
    assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex");
    ThreadBlockInVM tbivm ((JavaThread *) Self) ;
    ILock (Self) ;
  } else {
    // Mirabile dictu
    ILock (Self) ;
  }
  goto Exeunt ;
}
 

 

 

JNI lock(Unsafe monitorEnter、monitorExit、tryMonitorEnter)参考另一篇文章:https://lobin.iteye.com/blog/2327670

分享到:
评论

相关推荐

    java的Lock锁原理详解.docx

    Lock接口提供了比synchronized更丰富的功能,如尝试获取锁(tryLock)、可中断的锁获取(lockInterruptibly)、超时获取锁(tryLock(long time, TimeUnit unit))以及显式解锁(unlock)。Lock接口的实现类,例如...

    JVM 完整深入解析.pdf

    JMM定义了若干规则来保证线程间的交互操作,这些操作包括:lock(锁定)、unlock(解锁)、read(读取)、load(载入)、use(使用)、assign(赋值)、store(存储)和write(写入)。这些操作确保了在虚拟机内部...

    synchronized和LOCK的实现原理深入JVM锁机制比较好.docx

    了解 JVM 锁机制中的 synchronized 和 Lock 实现原理 在 Java 中,锁机制是数据同步的关键,存在两种锁机制:synchronized 和 Lock。了解这两种锁机制的实现原理对于理解 Java 并发编程非常重要。 synchronized 锁...

    nanodav:小型的基本WebDAV服务器

    描述使用伪造的LOCK / UNLOCK实现对OS X Finder的部分2类支持的1类WebDAV服务器。用法运行提供的android-app和java-app演示应用程序将其包含在您自己的项目中: 在Android上:将源文件从lib /目录复制到您的项目中。...

    Lock接口与synchronized关键字

    - **synchronized**通常比Lock接口开销更小,因为它是由JVM内置支持的,经过高度优化。 - 然而,在高度竞争的并发场景下,Lock接口可能会表现出更好的性能,尤其是在利用其额外的功能特性时。 #### 五、示例代码 ...

    java的lock和synchronized的区别.docx

    ReentrantLock 加锁(lock())、释放锁(unlock()) ### 5. 解释说明 有了 synchronized 关键字,为什么还需要 lock 这个接口类呢?synchronized 的不足: 1. 如果获取锁的线程等待被执行的代码块是被阻塞了...

    JVM 完整深入解析.docx

    - JMM通过内存间交互操作如lock、unlock、read、load、use、assign、store和write来协调线程之间的数据同步。 理解JVM内存管理和JMM对于编写高性能、线程安全的Java程序至关重要,因为它们直接影响程序的运行效率和...

    wait,notify等线程知识.pdf

    `Lock` 接口中定义了 `lock()` 和 `unlock()` 方法来显式地控制锁的获取和释放,还提供了 `tryLock()` 方法尝试获取锁而不阻塞线程。 **示例代码:** ```java Lock lock = new ReentrantLock(); lock.lock(); try {...

    java synchronized关键字原理、自定义一把锁来实现同步等

    4. **Lock 和 Unlock**: `lock` 方法使用 `while` 循环尝试获取锁,若获取失败则继续尝试;`unlock` 方法简单地将 `state` 设为 0 来释放锁。 #### 四、自定义锁测试 为了验证自定义锁的效果,我们可以创建多个...

    多线程学习代码

    lock.unlock(); } ``` 在多线程环境下,正确地使用锁可以避免数据不一致性和竞态条件。然而,过度使用锁可能导致性能下降,因此需要谨慎设计并发策略。 最后,JVM特性是Java程序高效运行的基础。JVM(Java虚拟机...

    Java lock同步锁使用实例解析

    不但可以通过一些监控工具监控synchronized的锁定,而且在代码执行时出现异常,JVM会自动释放锁定,但是使用Lock则不行,lock是通过代码实现的,要保证锁定一定会被释放,就必须将unLock()放到finally{} 中。...

    Java线程同步Lock同步锁代码示例

    draw方法实现了取钱的同步操作,使用lock.lock()和lock.unlock()方法来加锁和解锁,确保取钱操作的安全性。 Java线程同步Lock同步锁是Java提供的一种强大的线程同步机制,通过显示定义同步锁对象来实现同步,确保...

    java中的锁

    lock.unlock(); // 释放锁 } ``` 三、锁的特性 1. 可重入性:允许同一个线程多次获取同一把锁,不会发生死锁。 2. 公平性:ReentrantLock可设置为公平锁,按照请求锁的顺序进行分配,避免“线程饥饿”。 3. 非...

    深入Synchronized和java.util.concurrent.locks.Lock的区别详解

    使用Lock时,程序员需要显式地调用lock()来获取锁,并在finally块中确保调用unlock()来释放锁,这增加了代码的复杂性,但也带来了更高的控制度。Lock的优势在于它支持更细粒度的锁控制,可以提高并发性能,因为它...

    locktest.zip

    2. **非块结构**:使用Lock时,我们不需要像`synchronized`那样包围整个代码块,而是需要在适当的地方显式调用`lock()`和`unlock()`方法。 3. **可中断性**:Lock的`lockInterruptibly()`方法允许在等待锁时响应中断...

    Java 编程 线程调度 死锁避免

    lock1.unlock(); } } public void method2() { lock2.lock(); try { // Do something with resource 2 } finally { lock2.unlock(); } } } ``` 在这个例子中,如果`method1`先获取`lock1`,然后调用`...

    Java多线程中Lock锁的使用总结

    Lock接口提供了锁定的基本操作,包括lock()、unlock()和tryLock()等方法。Lock接口可以实现独占锁和共享锁两种锁机制。 知识点5: Java中的ReentrantLock Java中的ReentrantLock是Java中的一个Lock实现类。...

    分布式锁的实现方案.doc

    redisLock.unlock(); ``` **RedLock算法**:RedLock是由Redis作者Antirez提出的,它通过在多个独立的Redis实例上获取锁来提高锁的可用性和可靠性。如果大多数实例都返回成功,那么锁被认为已成功获取。这样可以减少...

    Java concurrency之Condition条件_动力节点Java学院整理

    lock.unlock(); } } static class ThreadA implements Runnable { private final Condition condition; public ThreadA(Condition condition) { this.condition = condition; } @Override public void ...

Global site tag (gtag.js) - Google Analytics