src/share/vm/runtime/objectMonitor.cpp

Print this page


   1 /*
   2  * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *


 365   assert (_succ  != Self          , "invariant") ;
 366   assert (Self->is_Java_thread()  , "invariant") ;
 367   JavaThread * jt = (JavaThread *) Self ;
 368   assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
 369   assert (jt->thread_state() != _thread_blocked   , "invariant") ;
 370   assert (this->object() != NULL  , "invariant") ;
 371   assert (_count >= 0, "invariant") ;
 372 
 373   // Prevent deflation at STW-time.  See deflate_idle_monitors() and is_busy().
 374   // Ensure the object-monitor relationship remains stable while there's contention.
 375   Atomic::inc_ptr(&_count);
 376 
 377   EventJavaMonitorEnter event;
 378 
 379   { // Change java thread status to indicate blocked on monitor enter.
 380     JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
 381 
 382     DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
 383     if (JvmtiExport::should_post_monitor_contended_enter()) {
 384       JvmtiExport::post_monitor_contended_enter(jt, this);






 385     }
 386 
 387     OSThreadContendState osts(Self->osthread());
 388     ThreadBlockInVM tbivm(jt);
 389 
 390     Self->set_current_pending_monitor(this);
 391 
 392     // TODO-FIXME: change the following for(;;) loop to straight-line code.
 393     for (;;) {
 394       jt->set_suspend_equivalent();
 395       // cleared by handle_special_suspend_equivalent_condition()
 396       // or java_suspend_self()
 397 
 398       EnterI (THREAD) ;
 399 
 400       if (!ExitSuspendEquivalent(jt)) break ;
 401 
 402       //
 403       // We have acquired the contended monitor, but while we were
 404       // waiting another thread suspended us. We don't want to enter


 422   assert (_recursions == 0     , "invariant") ;
 423   assert (_owner == Self       , "invariant") ;
 424   assert (_succ  != Self       , "invariant") ;
 425   assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
 426 
 427   // The thread -- now the owner -- is back in vm mode.
 428   // Report the glorious news via TI,DTrace and jvmstat.
 429   // The probe effect is non-trivial.  All the reportage occurs
 430   // while we hold the monitor, increasing the length of the critical
 431   // section.  Amdahl's parallel speedup law comes vividly into play.
 432   //
 433   // Another option might be to aggregate the events (thread local or
 434   // per-monitor aggregation) and defer reporting until a more opportune
 435   // time -- such as next time some thread encounters contention but has
 436   // yet to acquire the lock.  While spinning that thread could
 437   // spinning we could increment JVMStat counters, etc.
 438 
 439   DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt);
 440   if (JvmtiExport::should_post_monitor_contended_entered()) {
 441     JvmtiExport::post_monitor_contended_entered(jt, this);






 442   }
 443 
 444   if (event.should_commit()) {
 445     event.set_klass(((oop)this->object())->klass());
 446     event.set_previousOwner((TYPE_JAVALANGTHREAD)_previous_owner_tid);
 447     event.set_address((TYPE_ADDRESS)(uintptr_t)(this->object_addr()));
 448     event.commit();
 449   }
 450 
 451   if (ObjectMonitor::_sync_ContendedLockAttempts != NULL) {
 452      ObjectMonitor::_sync_ContendedLockAttempts->inc() ;
 453   }
 454 }
 455 
 456 
 457 // Caveat: TryLock() is not necessarily serializing if it returns failure.
 458 // Callers must compensate as needed.
 459 
 460 int ObjectMonitor::TryLock (Thread * Self) {
 461    for (;;) {


1439 // will need to be replicated in complete_exit above
1440 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
1441    Thread * const Self = THREAD ;
1442    assert(Self->is_Java_thread(), "Must be Java thread!");
1443    JavaThread *jt = (JavaThread *)THREAD;
1444 
1445    DeferredInitialize () ;
1446 
1447    // Throw IMSX or IEX.
1448    CHECK_OWNER();
1449 
1450    EventJavaMonitorWait event;
1451 
1452    // check for a pending interrupt
1453    if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
1454      // post monitor waited event.  Note that this is past-tense, we are done waiting.
1455      if (JvmtiExport::should_post_monitor_waited()) {
1456         // Note: 'false' parameter is passed here because the
1457         // wait was not timed out due to thread interrupt.
1458         JvmtiExport::post_monitor_waited(jt, this, false);








1459      }
1460      if (event.should_commit()) {
1461        post_monitor_wait_event(&event, 0, millis, false);
1462      }
1463      TEVENT (Wait - Throw IEX) ;
1464      THROW(vmSymbols::java_lang_InterruptedException());
1465      return ;
1466    }
1467 
1468    TEVENT (Wait) ;
1469 
1470    assert (Self->_Stalled == 0, "invariant") ;
1471    Self->_Stalled = intptr_t(this) ;
1472    jt->set_current_waiting_monitor(this);
1473 
1474    // create a node to be put into the queue
1475    // Critically, after we reset() the event but prior to park(), we must check
1476    // for a pending interrupt.
1477    ObjectWaiter node(Self);
1478    node.TState = ObjectWaiter::TS_WAIT ;


1482    // Enter the waiting queue, which is a circular doubly linked list in this case
1483    // but it could be a priority queue or any data structure.
1484    // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1485    // by the the owner of the monitor *except* in the case where park()
1486    // returns because of a timeout of interrupt.  Contention is exceptionally rare
1487    // so we use a simple spin-lock instead of a heavier-weight blocking lock.
1488 
1489    Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ;
1490    AddWaiter (&node) ;
1491    Thread::SpinRelease (&_WaitSetLock) ;
1492 
1493    if ((SyncFlags & 4) == 0) {
1494       _Responsible = NULL ;
1495    }
1496    intptr_t save = _recursions; // record the old recursion count
1497    _waiters++;                  // increment the number of waiters
1498    _recursions = 0;             // set the recursion level to be 1
1499    exit (true, Self) ;                    // exit the monitor
1500    guarantee (_owner != Self, "invariant") ;
1501 
1502    // As soon as the ObjectMonitor's ownership is dropped in the exit()
1503    // call above, another thread can enter() the ObjectMonitor, do the
1504    // notify(), and exit() the ObjectMonitor. If the other thread's
1505    // exit() call chooses this thread as the successor and the unpark()
1506    // call happens to occur while this thread is posting a
1507    // MONITOR_CONTENDED_EXIT event, then we run the risk of the event
1508    // handler using RawMonitors and consuming the unpark().
1509    //
1510    // To avoid the problem, we re-post the event. This does no harm
1511    // even if the original unpark() was not consumed because we are the
1512    // chosen successor for this monitor.
1513    if (node._notified != 0 && _succ == Self) {
1514       node._event->unpark();
1515    }
1516 
1517    // The thread is on the WaitSet list - now park() it.
1518    // On MP systems it's conceivable that a brief spin before we park
1519    // could be profitable.
1520    //
1521    // TODO-FIXME: change the following logic to a loop of the form
1522    //   while (!timeout && !interrupted && _notified == 0) park()
1523 
1524    int ret = OS_OK ;
1525    int WasNotified = 0 ;
1526    { // State transition wrappers
1527      OSThread* osthread = Self->osthread();
1528      OSThreadWaitState osts(osthread, true);
1529      {
1530        ThreadBlockInVM tbivm(jt);
1531        // Thread is in thread_blocked state and oop access is unsafe.
1532        jt->set_suspend_equivalent();
1533 
1534        if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
1535            // Intentionally empty
1536        } else


1580      // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
1581      // The Node's TState variable is stable from the perspective of this thread.
1582      // No other threads will asynchronously modify TState.
1583      guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ;
1584      OrderAccess::loadload() ;
1585      if (_succ == Self) _succ = NULL ;
1586      WasNotified = node._notified ;
1587 
1588      // Reentry phase -- reacquire the monitor.
1589      // re-enter contended monitor after object.wait().
1590      // retain OBJECT_WAIT state until re-enter successfully completes
1591      // Thread state is thread_in_vm and oop access is again safe,
1592      // although the raw address of the object may have changed.
1593      // (Don't cache naked oops over safepoints, of course).
1594 
1595      // post monitor waited event. Note that this is past-tense, we are done waiting.
1596      if (JvmtiExport::should_post_monitor_waited()) {
1597        JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
1598      }
1599 



























1600      if (event.should_commit()) {
1601        post_monitor_wait_event(&event, node._notifier_tid, millis, ret == OS_TIMEOUT);
1602      }
1603 
1604      OrderAccess::fence() ;
1605 
1606      assert (Self->_Stalled != 0, "invariant") ;
1607      Self->_Stalled = 0 ;
1608 
1609      assert (_owner != Self, "invariant") ;
1610      ObjectWaiter::TStates v = node.TState ;
1611      if (v == ObjectWaiter::TS_RUN) {
1612          enter (Self) ;
1613      } else {
1614          guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
1615          ReenterI (Self, &node) ;
1616          node.wait_reenter_end(this);
1617      }
1618 
1619      // Self has reacquired the lock.


   1 /*
   2  * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *


 365   assert (_succ  != Self          , "invariant") ;
 366   assert (Self->is_Java_thread()  , "invariant") ;
 367   JavaThread * jt = (JavaThread *) Self ;
 368   assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
 369   assert (jt->thread_state() != _thread_blocked   , "invariant") ;
 370   assert (this->object() != NULL  , "invariant") ;
 371   assert (_count >= 0, "invariant") ;
 372 
 373   // Prevent deflation at STW-time.  See deflate_idle_monitors() and is_busy().
 374   // Ensure the object-monitor relationship remains stable while there's contention.
 375   Atomic::inc_ptr(&_count);
 376 
 377   EventJavaMonitorEnter event;
 378 
 379   { // Change java thread status to indicate blocked on monitor enter.
 380     JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
 381 
 382     DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
 383     if (JvmtiExport::should_post_monitor_contended_enter()) {
 384       JvmtiExport::post_monitor_contended_enter(jt, this);
 385 
 386       // The current thread does not yet own the monitor and does not
 387       // yet appear on any queues that would get it made the successor.
 388       // This means that the JVMTI_EVENT_MONITOR_CONTENDED_ENTER event
 389       // handler cannot accidentally consume an unpark() meant for the
 390       // ParkEvent associated with this ObjectMonitor.
 391     }
 392 
 393     OSThreadContendState osts(Self->osthread());
 394     ThreadBlockInVM tbivm(jt);
 395 
 396     Self->set_current_pending_monitor(this);
 397 
 398     // TODO-FIXME: change the following for(;;) loop to straight-line code.
 399     for (;;) {
 400       jt->set_suspend_equivalent();
 401       // cleared by handle_special_suspend_equivalent_condition()
 402       // or java_suspend_self()
 403 
 404       EnterI (THREAD) ;
 405 
 406       if (!ExitSuspendEquivalent(jt)) break ;
 407 
 408       //
 409       // We have acquired the contended monitor, but while we were
 410       // waiting another thread suspended us. We don't want to enter


 428   assert (_recursions == 0     , "invariant") ;
 429   assert (_owner == Self       , "invariant") ;
 430   assert (_succ  != Self       , "invariant") ;
 431   assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
 432 
 433   // The thread -- now the owner -- is back in vm mode.
 434   // Report the glorious news via TI,DTrace and jvmstat.
 435   // The probe effect is non-trivial.  All the reportage occurs
 436   // while we hold the monitor, increasing the length of the critical
 437   // section.  Amdahl's parallel speedup law comes vividly into play.
 438   //
 439   // Another option might be to aggregate the events (thread local or
 440   // per-monitor aggregation) and defer reporting until a more opportune
 441   // time -- such as next time some thread encounters contention but has
 442   // yet to acquire the lock.  While spinning that thread could
 443   // spinning we could increment JVMStat counters, etc.
 444 
 445   DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt);
 446   if (JvmtiExport::should_post_monitor_contended_entered()) {
 447     JvmtiExport::post_monitor_contended_entered(jt, this);
 448 
 449     // The current thread already owns the monitor and is not going to
 450     // call park() for the remainder of the monitor enter protocol. So
 451     // it doesn't matter if the JVMTI_EVENT_MONITOR_CONTENDED_ENTERED
 452     // event handler consumed an unpark() issued by the thread that
 453     // just exited the monitor.
 454   }
 455 
 456   if (event.should_commit()) {
 457     event.set_klass(((oop)this->object())->klass());
 458     event.set_previousOwner((TYPE_JAVALANGTHREAD)_previous_owner_tid);
 459     event.set_address((TYPE_ADDRESS)(uintptr_t)(this->object_addr()));
 460     event.commit();
 461   }
 462 
 463   if (ObjectMonitor::_sync_ContendedLockAttempts != NULL) {
 464      ObjectMonitor::_sync_ContendedLockAttempts->inc() ;
 465   }
 466 }
 467 
 468 
 469 // Caveat: TryLock() is not necessarily serializing if it returns failure.
 470 // Callers must compensate as needed.
 471 
 472 int ObjectMonitor::TryLock (Thread * Self) {
 473    for (;;) {


1451 // will need to be replicated in complete_exit above
1452 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
1453    Thread * const Self = THREAD ;
1454    assert(Self->is_Java_thread(), "Must be Java thread!");
1455    JavaThread *jt = (JavaThread *)THREAD;
1456 
1457    DeferredInitialize () ;
1458 
1459    // Throw IMSX or IEX.
1460    CHECK_OWNER();
1461 
1462    EventJavaMonitorWait event;
1463 
1464    // check for a pending interrupt
1465    if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
1466      // post monitor waited event.  Note that this is past-tense, we are done waiting.
1467      if (JvmtiExport::should_post_monitor_waited()) {
1468         // Note: 'false' parameter is passed here because the
1469         // wait was not timed out due to thread interrupt.
1470         JvmtiExport::post_monitor_waited(jt, this, false);
1471 
1472         // In this short circuit of the monitor wait protocol, the
1473         // current thread never drops ownership of the monitor and
1474         // never gets added to the wait queue so the current thread
1475         // cannot be made the successor. This means that the
1476         // JVMTI_EVENT_MONITOR_WAITED event handler cannot accidentally
1477         // consume an unpark() meant for the ParkEvent associated with
1478         // this ObjectMonitor.
1479      }
1480      if (event.should_commit()) {
1481        post_monitor_wait_event(&event, 0, millis, false);
1482      }
1483      TEVENT (Wait - Throw IEX) ;
1484      THROW(vmSymbols::java_lang_InterruptedException());
1485      return ;
1486    }
1487 
1488    TEVENT (Wait) ;
1489 
1490    assert (Self->_Stalled == 0, "invariant") ;
1491    Self->_Stalled = intptr_t(this) ;
1492    jt->set_current_waiting_monitor(this);
1493 
1494    // create a node to be put into the queue
1495    // Critically, after we reset() the event but prior to park(), we must check
1496    // for a pending interrupt.
1497    ObjectWaiter node(Self);
1498    node.TState = ObjectWaiter::TS_WAIT ;


1502    // Enter the waiting queue, which is a circular doubly linked list in this case
1503    // but it could be a priority queue or any data structure.
1504    // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1505    // by the the owner of the monitor *except* in the case where park()
1506    // returns because of a timeout of interrupt.  Contention is exceptionally rare
1507    // so we use a simple spin-lock instead of a heavier-weight blocking lock.
1508 
1509    Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ;
1510    AddWaiter (&node) ;
1511    Thread::SpinRelease (&_WaitSetLock) ;
1512 
1513    if ((SyncFlags & 4) == 0) {
1514       _Responsible = NULL ;
1515    }
1516    intptr_t save = _recursions; // record the old recursion count
1517    _waiters++;                  // increment the number of waiters
1518    _recursions = 0;             // set the recursion level to be 1
1519    exit (true, Self) ;                    // exit the monitor
1520    guarantee (_owner != Self, "invariant") ;
1521 















1522    // The thread is on the WaitSet list - now park() it.
1523    // On MP systems it's conceivable that a brief spin before we park
1524    // could be profitable.
1525    //
1526    // TODO-FIXME: change the following logic to a loop of the form
1527    //   while (!timeout && !interrupted && _notified == 0) park()
1528 
1529    int ret = OS_OK ;
1530    int WasNotified = 0 ;
1531    { // State transition wrappers
1532      OSThread* osthread = Self->osthread();
1533      OSThreadWaitState osts(osthread, true);
1534      {
1535        ThreadBlockInVM tbivm(jt);
1536        // Thread is in thread_blocked state and oop access is unsafe.
1537        jt->set_suspend_equivalent();
1538 
1539        if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
1540            // Intentionally empty
1541        } else


1585      // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
1586      // The Node's TState variable is stable from the perspective of this thread.
1587      // No other threads will asynchronously modify TState.
1588      guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ;
1589      OrderAccess::loadload() ;
1590      if (_succ == Self) _succ = NULL ;
1591      WasNotified = node._notified ;
1592 
1593      // Reentry phase -- reacquire the monitor.
1594      // re-enter contended monitor after object.wait().
1595      // retain OBJECT_WAIT state until re-enter successfully completes
1596      // Thread state is thread_in_vm and oop access is again safe,
1597      // although the raw address of the object may have changed.
1598      // (Don't cache naked oops over safepoints, of course).
1599 
1600      // post monitor waited event. Note that this is past-tense, we are done waiting.
1601      if (JvmtiExport::should_post_monitor_waited()) {
1602        JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
1603      }
1604 
1605      // Without the fix for 8028280, it is possible for the above call:
1606      //
1607      //   Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ;
1608      //
1609      // to consume the unpark() that was done when the successor was set.
1610      // The solution for this very rare possibility is to redo the unpark()
1611      // outside of the JvmtiExport::should_post_monitor_waited() check.
1612      //
1613      if (node._notified != 0 && _succ == Self) {
1614        // In this part of the monitor wait-notify-reenter protocol it
1615        // is possible (and normal) for another thread to do a fastpath
1616        // monitor enter-exit while this thread is still trying to get
1617        // to the reenter portion of the protocol.
1618        //
1619        // The ObjectMonitor was notified and the current thread is
1620        // the successor which also means that an unpark() has already
1621        // been done. The JVMTI_EVENT_MONITOR_WAITED event handler can
1622        // consume the unpark() that was done when the successor was
1623        // set because the same ParkEvent is shared between Java
1624        // monitors and JVM/TI RawMonitors (for now).
1625        //
1626        // We redo the unpark() to ensure forward progress, i.e., we
1627        // don't want all pending threads hanging (parked) with none
1628        // entering the unlocked monitor.
1629        node._event->unpark();
1630      }
1631 
1632      if (event.should_commit()) {
1633        post_monitor_wait_event(&event, node._notifier_tid, millis, ret == OS_TIMEOUT);
1634      }
1635 
1636      OrderAccess::fence() ;
1637 
1638      assert (Self->_Stalled != 0, "invariant") ;
1639      Self->_Stalled = 0 ;
1640 
1641      assert (_owner != Self, "invariant") ;
1642      ObjectWaiter::TStates v = node.TState ;
1643      if (v == ObjectWaiter::TS_RUN) {
1644          enter (Self) ;
1645      } else {
1646          guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
1647          ReenterI (Self, &node) ;
1648          node.wait_reenter_end(this);
1649      }
1650 
1651      // Self has reacquired the lock.