< prev index next >

src/share/vm/runtime/thread.cpp

Print this page




  78 #include "runtime/threadCritical.hpp"
  79 #include "runtime/threadLocalStorage.hpp"
  80 #include "runtime/vframe.hpp"
  81 #include "runtime/vframeArray.hpp"
  82 #include "runtime/vframe_hp.hpp"
  83 #include "runtime/vmThread.hpp"
  84 #include "runtime/vm_operations.hpp"
  85 #include "runtime/vm_version.hpp"
  86 #include "services/attachListener.hpp"
  87 #include "services/management.hpp"
  88 #include "services/memTracker.hpp"
  89 #include "services/threadService.hpp"
  90 #include "trace/traceMacros.hpp"
  91 #include "trace/tracing.hpp"
  92 #include "utilities/defaultStream.hpp"
  93 #include "utilities/dtrace.hpp"
  94 #include "utilities/events.hpp"
  95 #include "utilities/macros.hpp"
  96 #include "utilities/preserveException.hpp"
  97 #if INCLUDE_ALL_GCS

  98 #include "gc/cms/concurrentMarkSweepThread.hpp"
  99 #include "gc/g1/concurrentMarkThread.inline.hpp"
 100 #include "gc/parallel/pcTasks.hpp"
 101 #endif // INCLUDE_ALL_GCS
 102 #ifdef COMPILER1
 103 #include "c1/c1_Compiler.hpp"
 104 #endif
 105 #ifdef COMPILER2
 106 #include "opto/c2compiler.hpp"
 107 #include "opto/idealGraphPrinter.hpp"
 108 #endif
 109 #if INCLUDE_RTM_OPT
 110 #include "runtime/rtmLocking.hpp"
 111 #endif
 112 
 113 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 114 
 115 #ifdef DTRACE_ENABLED
 116 
 117 // Only bother with this argument setup if dtrace is available


 245   _hashStateZ = 0x8767;    // (int)(3579807591LL & 0xffff) ;
 246   _hashStateW = 273326509;
 247 
 248   _OnTrap   = 0;
 249   _schedctl = NULL;
 250   _Stalled  = 0;
 251   _TypeTag  = 0x2BAD;
 252 
 253   // Many of the following fields are effectively final - immutable
 254   // Note that nascent threads can't use the Native Monitor-Mutex
 255   // construct until the _MutexEvent is initialized ...
 256   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 257   // we might instead use a stack of ParkEvents that we could provision on-demand.
 258   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 259   // and ::Release()
 260   _ParkEvent   = ParkEvent::Allocate(this);
 261   _SleepEvent  = ParkEvent::Allocate(this);
 262   _MutexEvent  = ParkEvent::Allocate(this);
 263   _MuxEvent    = ParkEvent::Allocate(this);
 264 


 265 #ifdef CHECK_UNHANDLED_OOPS
 266   if (CheckUnhandledOops) {
 267     _unhandled_oops = new UnhandledOops(this);
 268   }
 269 #endif // CHECK_UNHANDLED_OOPS
 270 #ifdef ASSERT
 271   if (UseBiasedLocking) {
 272     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 273     assert(this == _real_malloc_address ||
 274            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
 275            "bug in forced alignment of thread objects");
 276   }
 277 #endif // ASSERT
 278 }
 279 
 280 // Non-inlined version to be used where thread.inline.hpp shouldn't be included.
 281 Thread* Thread::current_noinline() {
 282   return Thread::current();
 283 }
 284 


1248       break;
1249     }
1250 
1251     remaining = PeriodicTask::time_to_wait();
1252     if (remaining == 0) {
1253       // Last task was just disenrolled so loop around and wait until
1254       // another task gets enrolled
1255       continue;
1256     }
1257 
1258     remaining -= time_slept;
1259     if (remaining <= 0) {
1260       break;
1261     }
1262   }
1263 
1264   return time_slept;
1265 }
1266 
1267 void WatcherThread::run() {

1268   assert(this == watcher_thread(), "just checking");
1269 
1270   this->record_stack_base_and_size();
1271   this->initialize_thread_local_storage();
1272   this->set_native_thread_name(this->name());
1273   this->set_active_handles(JNIHandleBlock::allocate_block());
1274   while (true) {
1275     assert(watcher_thread() == Thread::current(), "thread consistency check");
1276     assert(watcher_thread() == this, "thread consistency check");
1277 
1278     // Calculate how long it'll be until the next PeriodicTask work
1279     // should be done, and sleep that amount of time.
1280     int time_waited = sleep();
1281 
1282     if (is_error_reported()) {
1283       // A fatal error has happened, the error handler(VMError::report_and_die)
1284       // should abort JVM after creating an error log file. However in some
1285       // rare cases, the error handler itself might deadlock. Here we try to
1286       // kill JVM if the fatal error handler fails to abort in 2 minutes.
1287       //


1454     set_thread_profiler(pp);
1455   }
1456 
1457   // Setup safepoint state info for this thread
1458   ThreadSafepointState::create(this);
1459 
1460   debug_only(_java_call_counter = 0);
1461 
1462   // JVMTI PopFrame support
1463   _popframe_condition = popframe_inactive;
1464   _popframe_preserved_args = NULL;
1465   _popframe_preserved_args_size = 0;
1466   _frames_to_pop_failed_realloc = 0;
1467 
1468   pd_initialize();
1469 }
1470 
1471 #if INCLUDE_ALL_GCS
1472 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
1473 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;

1474 #endif // INCLUDE_ALL_GCS
1475 
1476 JavaThread::JavaThread(bool is_attaching_via_jni) :
1477                        Thread()
1478 #if INCLUDE_ALL_GCS
1479                        , _satb_mark_queue(&_satb_mark_queue_set),
1480                        _dirty_card_queue(&_dirty_card_queue_set)

1481 #endif // INCLUDE_ALL_GCS
1482 {
1483   initialize();
1484   if (is_attaching_via_jni) {
1485     _jni_attach_state = _attaching_via_jni;
1486   } else {
1487     _jni_attach_state = _not_attaching_via_jni;
1488   }
1489   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1490 }
1491 
1492 bool JavaThread::reguard_stack(address cur_sp) {
1493   if (_stack_guard_state != stack_guard_yellow_disabled) {
1494     return true; // Stack already guarded or guard pages not needed.
1495   }
1496 
1497   if (register_stack_overflow()) {
1498     // For those architectures which have separate register and
1499     // memory stacks, we must check the register stack to see if
1500     // it has overflowed.


1518 
1519 
1520 void JavaThread::block_if_vm_exited() {
1521   if (_terminated == _vm_exited) {
1522     // _vm_exited is set at safepoint, and Threads_lock is never released
1523     // we will block here forever
1524     Threads_lock->lock_without_safepoint_check();
1525     ShouldNotReachHere();
1526   }
1527 }
1528 
1529 
1530 // Remove this ifdef when C1 is ported to the compiler interface.
1531 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1532 static void sweeper_thread_entry(JavaThread* thread, TRAPS);
1533 
1534 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1535                        Thread()
1536 #if INCLUDE_ALL_GCS
1537                        , _satb_mark_queue(&_satb_mark_queue_set),
1538                        _dirty_card_queue(&_dirty_card_queue_set)

1539 #endif // INCLUDE_ALL_GCS
1540 {
1541   initialize();
1542   _jni_attach_state = _not_attaching_via_jni;
1543   set_entry_point(entry_point);
1544   // Create the native thread itself.
1545   // %note runtime_23
1546   os::ThreadType thr_type = os::java_thread;
1547   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1548                                                      os::java_thread;
1549   os::create_thread(this, thr_type, stack_sz);
1550   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1551   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1552   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1553   // the exception consists of creating the exception object & initializing it, initialization
1554   // will leave the VM via a JavaCall and then all locks must be unlocked).
1555   //
1556   // The thread is still suspended when we reach here. Thread must be explicit started
1557   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1558   // by calling Threads:add. The reason why this is not done here, is because the thread


1653   // Note: Due to JVM_StopThread we can have pending exceptions already!
1654   if (!this->has_pending_exception() &&
1655       !java_lang_Thread::is_stillborn(this->threadObj())) {
1656     {
1657       ResourceMark rm(this);
1658       this->set_native_thread_name(this->get_thread_name());
1659     }
1660     HandleMark hm(this);
1661     this->entry_point()(this, this);
1662   }
1663 
1664   DTRACE_THREAD_PROBE(stop, this);
1665 
1666   this->exit(false);
1667   delete this;
1668 }
1669 
1670 
1671 static void ensure_join(JavaThread* thread) {
1672   // We do not need to grap the Threads_lock, since we are operating on ourself.
1673   Handle threadObj(thread, thread->threadObj());
1674   assert(threadObj.not_null(), "java thread object must exist");
1675   ObjectLocker lock(threadObj, thread);
1676   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1677   thread->clear_pending_exception();
1678   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1679   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1680   // Clear the native thread instance - this makes isAlive return false and allows the join()
1681   // to complete once we've done the notify_all below
1682   java_lang_Thread::set_thread(threadObj(), NULL);
1683   lock.notify_all(thread);
1684   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1685   thread->clear_pending_exception();
1686 }
1687 
1688 
1689 // For any new cleanup additions, please check to see if they need to be applied to
1690 // cleanup_failed_attach_current_thread as well.
1691 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1692   assert(this == JavaThread::current(), "thread consistency check");
1693 


1847   remove_stack_guard_pages();
1848 
1849   if (UseTLAB) {
1850     tlab().make_parsable(true);  // retire TLAB
1851   }
1852 
1853   if (JvmtiEnv::environments_might_exist()) {
1854     JvmtiExport::cleanup_thread(this);
1855   }
1856 
1857   // We must flush any deferred card marks before removing a thread from
1858   // the list of active threads.
1859   Universe::heap()->flush_deferred_store_barrier(this);
1860   assert(deferred_card_mark().is_empty(), "Should have been flushed");
1861 
1862 #if INCLUDE_ALL_GCS
1863   // We must flush the G1-related buffers before removing a thread
1864   // from the list of active threads. We must do this after any deferred
1865   // card marks have been flushed (above) so that any entries that are
1866   // added to the thread's dirty card queue as a result are not lost.
1867   if (UseG1GC) {
1868     flush_barrier_queues();
1869   }



1870 #endif // INCLUDE_ALL_GCS
1871 
1872   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1873   Threads::remove(this);
1874 }
1875 
1876 #if INCLUDE_ALL_GCS
1877 // Flush G1-related queues.
1878 void JavaThread::flush_barrier_queues() {
1879   satb_mark_queue().flush();
1880   dirty_card_queue().flush();
1881 }
1882 
1883 void JavaThread::initialize_queues() {
1884   assert(!SafepointSynchronize::is_at_safepoint(),
1885          "we should not be at a safepoint");
1886 
1887   ObjPtrQueue& satb_queue = satb_mark_queue();
1888   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
1889   // The SATB queue should have been constructed with its active
1890   // field set to false.
1891   assert(!satb_queue.is_active(), "SATB queue should not be active");
1892   assert(satb_queue.is_empty(), "SATB queue should be empty");
1893   // If we are creating the thread during a marking cycle, we should
1894   // set the active field of the SATB queue to true.
1895   if (satb_queue_set.is_active()) {
1896     satb_queue.set_active(true);
1897   }
1898 
1899   DirtyCardQueue& dirty_queue = dirty_card_queue();
1900   // The dirty card queue should have been constructed with its
1901   // active field set to true.
1902   assert(dirty_queue.is_active(), "dirty card queue should be active");
1903 }















1904 #endif // INCLUDE_ALL_GCS
1905 
1906 void JavaThread::cleanup_failed_attach_current_thread() {
1907   if (get_thread_profiler() != NULL) {
1908     get_thread_profiler()->disengage();
1909     ResourceMark rm;
1910     get_thread_profiler()->print(get_thread_name());
1911   }
1912 
1913   if (active_handles() != NULL) {
1914     JNIHandleBlock* block = active_handles();
1915     set_active_handles(NULL);
1916     JNIHandleBlock::release_block(block);
1917   }
1918 
1919   if (free_handle_block() != NULL) {
1920     JNIHandleBlock* block = free_handle_block();
1921     set_free_handle_block(NULL);
1922     JNIHandleBlock::release_block(block);
1923   }
1924 
1925   // These have to be removed while this is still a valid thread.
1926   remove_stack_guard_pages();
1927 
1928   if (UseTLAB) {
1929     tlab().make_parsable(true);  // retire TLAB, if any
1930   }
1931 
1932 #if INCLUDE_ALL_GCS
1933   if (UseG1GC) {
1934     flush_barrier_queues();
1935   }



1936 #endif // INCLUDE_ALL_GCS
1937 
1938   Threads::remove(this);
1939   delete this;
1940 }
1941 
1942 
1943 
1944 
1945 JavaThread* JavaThread::active() {
1946   Thread* thread = ThreadLocalStorage::thread();
1947   assert(thread != NULL, "just checking");
1948   if (thread->is_Java_thread()) {
1949     return (JavaThread*) thread;
1950   } else {
1951     assert(thread->is_VM_thread(), "this must be a vm thread");
1952     VM_Operation* op = ((VMThread*) thread)->vm_operation();
1953     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
1954     assert(ret->is_Java_thread(), "must be a Java thread");
1955     return ret;


2864     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2865       name_str = "<no-name - thread is attaching>";
2866     } else {
2867       name_str = Thread::name();
2868     }
2869   } else {
2870     name_str = Thread::name();
2871   }
2872   assert(name_str != NULL, "unexpected NULL thread name");
2873   return name_str;
2874 }
2875 
2876 
2877 const char* JavaThread::get_threadgroup_name() const {
2878   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2879   oop thread_obj = threadObj();
2880   if (thread_obj != NULL) {
2881     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2882     if (thread_group != NULL) {
2883       typeArrayOop name = java_lang_ThreadGroup::name(thread_group);

2884       // ThreadGroup.name can be null
2885       if (name != NULL) {
2886         const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2887         return str;
2888       }
2889     }
2890   }
2891   return NULL;
2892 }
2893 
2894 const char* JavaThread::get_parent_name() const {
2895   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2896   oop thread_obj = threadObj();
2897   if (thread_obj != NULL) {
2898     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2899     if (thread_group != NULL) {
2900       oop parent = java_lang_ThreadGroup::parent(thread_group);
2901       if (parent != NULL) {
2902         typeArrayOop name = java_lang_ThreadGroup::name(parent);

2903         // ThreadGroup.name can be null
2904         if (name != NULL) {
2905           const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2906           return str;
2907         }
2908       }
2909     }
2910   }
2911   return NULL;
2912 }
2913 
2914 ThreadPriority JavaThread::java_priority() const {
2915   oop thr_oop = threadObj();
2916   if (thr_oop == NULL) return NormPriority; // Bootstrapping
2917   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
2918   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
2919   return priority;
2920 }
2921 
2922 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {


3495   Metaspace::post_initialize();
3496 
3497   HOTSPOT_VM_INIT_END();
3498 
3499   // record VM initialization completion time
3500 #if INCLUDE_MANAGEMENT
3501   Management::record_vm_init_completed();
3502 #endif // INCLUDE_MANAGEMENT
3503 
3504   // Compute system loader. Note that this has to occur after set_init_completed, since
3505   // valid exceptions may be thrown in the process.
3506   // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3507   // set_init_completed has just been called, causing exceptions not to be shortcut
3508   // anymore. We call vm_exit_during_initialization directly instead.
3509   SystemDictionary::compute_java_system_loader(CHECK_JNI_ERR);
3510 
3511 #if INCLUDE_ALL_GCS
3512   // Support for ConcurrentMarkSweep. This should be cleaned up
3513   // and better encapsulated. The ugly nested if test would go away
3514   // once things are properly refactored. XXX YSR
3515   if (UseConcMarkSweepGC || UseG1GC) {
3516     if (UseConcMarkSweepGC) {
3517       ConcurrentMarkSweepThread::makeSurrogateLockerThread(CHECK_JNI_ERR);


3518     } else {
3519       ConcurrentMarkThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3520     }
3521   }
3522 #endif // INCLUDE_ALL_GCS
3523 
3524   // Always call even when there are not JVMTI environments yet, since environments
3525   // may be attached late and JVMTI must track phases of VM execution
3526   JvmtiExport::enter_live_phase();
3527 
3528   // Signal Dispatcher needs to be started before VMInit event is posted
3529   os::signal_init();
3530 
3531   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3532   if (!DisableAttachMechanism) {
3533     AttachListener::vm_start();
3534     if (StartAttachListener || AttachListener::init_at_startup()) {
3535       AttachListener::init();
3536     }
3537   }


3905       // complete. wait_for_ext_suspend_completion() will eventually
3906       // timeout, but that takes time. Making this wait a suspend-
3907       // equivalent condition solves that timeout problem.
3908       //
3909       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
3910                          Mutex::_as_suspend_equivalent_flag);
3911   }
3912 
3913   // Hang forever on exit if we are reporting an error.
3914   if (ShowMessageBoxOnError && is_error_reported()) {
3915     os::infinite_sleep();
3916   }
3917   os::wait_for_keypress_at_exit();
3918 
3919   // run Java level shutdown hooks
3920   thread->invoke_shutdown_hooks();
3921 
3922   before_exit(thread);
3923 
3924   thread->exit(true);



3925 
3926   // Stop VM thread.
3927   {
3928     // 4945125 The vm thread comes to a safepoint during exit.
3929     // GC vm_operations can get caught at the safepoint, and the
3930     // heap is unparseable if they are caught. Grab the Heap_lock
3931     // to prevent this. The GC vm_operations will not be able to
3932     // queue until after the vm thread is dead. After this point,
3933     // we'll never emerge out of the safepoint before the VM exits.
3934 
3935     MutexLocker ml(Heap_lock);
3936 
3937     VMThread::wait_for_vm_thread_exit();
3938     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
3939     VMThread::destroy();
3940   }
3941 
3942   // clean up ideal graph printers
3943 #if defined(COMPILER2) && !defined(PRODUCT)
3944   IdealGraphPrinter::clean_up();




  78 #include "runtime/threadCritical.hpp"
  79 #include "runtime/threadLocalStorage.hpp"
  80 #include "runtime/vframe.hpp"
  81 #include "runtime/vframeArray.hpp"
  82 #include "runtime/vframe_hp.hpp"
  83 #include "runtime/vmThread.hpp"
  84 #include "runtime/vm_operations.hpp"
  85 #include "runtime/vm_version.hpp"
  86 #include "services/attachListener.hpp"
  87 #include "services/management.hpp"
  88 #include "services/memTracker.hpp"
  89 #include "services/threadService.hpp"
  90 #include "trace/traceMacros.hpp"
  91 #include "trace/tracing.hpp"
  92 #include "utilities/defaultStream.hpp"
  93 #include "utilities/dtrace.hpp"
  94 #include "utilities/events.hpp"
  95 #include "utilities/macros.hpp"
  96 #include "utilities/preserveException.hpp"
  97 #if INCLUDE_ALL_GCS
  98 #include "gc/shenandoah/shenandoahConcurrentThread.hpp"
  99 #include "gc/cms/concurrentMarkSweepThread.hpp"
 100 #include "gc/g1/concurrentMarkThread.inline.hpp"
 101 #include "gc/parallel/pcTasks.hpp"
 102 #endif // INCLUDE_ALL_GCS
 103 #ifdef COMPILER1
 104 #include "c1/c1_Compiler.hpp"
 105 #endif
 106 #ifdef COMPILER2
 107 #include "opto/c2compiler.hpp"
 108 #include "opto/idealGraphPrinter.hpp"
 109 #endif
 110 #if INCLUDE_RTM_OPT
 111 #include "runtime/rtmLocking.hpp"
 112 #endif
 113 
 114 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 115 
 116 #ifdef DTRACE_ENABLED
 117 
 118 // Only bother with this argument setup if dtrace is available


 246   _hashStateZ = 0x8767;    // (int)(3579807591LL & 0xffff) ;
 247   _hashStateW = 273326509;
 248 
 249   _OnTrap   = 0;
 250   _schedctl = NULL;
 251   _Stalled  = 0;
 252   _TypeTag  = 0x2BAD;
 253 
 254   // Many of the following fields are effectively final - immutable
 255   // Note that nascent threads can't use the Native Monitor-Mutex
 256   // construct until the _MutexEvent is initialized ...
 257   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 258   // we might instead use a stack of ParkEvents that we could provision on-demand.
 259   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 260   // and ::Release()
 261   _ParkEvent   = ParkEvent::Allocate(this);
 262   _SleepEvent  = ParkEvent::Allocate(this);
 263   _MutexEvent  = ParkEvent::Allocate(this);
 264   _MuxEvent    = ParkEvent::Allocate(this);
 265 
 266   _evacuating = false;
 267 
 268 #ifdef CHECK_UNHANDLED_OOPS
 269   if (CheckUnhandledOops) {
 270     _unhandled_oops = new UnhandledOops(this);
 271   }
 272 #endif // CHECK_UNHANDLED_OOPS
 273 #ifdef ASSERT
 274   if (UseBiasedLocking) {
 275     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 276     assert(this == _real_malloc_address ||
 277            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
 278            "bug in forced alignment of thread objects");
 279   }
 280 #endif // ASSERT
 281 }
 282 
 283 // Non-inlined version to be used where thread.inline.hpp shouldn't be included.
 284 Thread* Thread::current_noinline() {
 285   return Thread::current();
 286 }
 287 


1251       break;
1252     }
1253 
1254     remaining = PeriodicTask::time_to_wait();
1255     if (remaining == 0) {
1256       // Last task was just disenrolled so loop around and wait until
1257       // another task gets enrolled
1258       continue;
1259     }
1260 
1261     remaining -= time_slept;
1262     if (remaining <= 0) {
1263       break;
1264     }
1265   }
1266 
1267   return time_slept;
1268 }
1269 
1270 void WatcherThread::run() {
1271 
1272   assert(this == watcher_thread(), "just checking");
1273 
1274   this->record_stack_base_and_size();
1275   this->initialize_thread_local_storage();
1276   this->set_native_thread_name(this->name());
1277   this->set_active_handles(JNIHandleBlock::allocate_block());
1278   while (true) {
1279     assert(watcher_thread() == Thread::current(), "thread consistency check");
1280     assert(watcher_thread() == this, "thread consistency check");
1281 
1282     // Calculate how long it'll be until the next PeriodicTask work
1283     // should be done, and sleep that amount of time.
1284     int time_waited = sleep();
1285 
1286     if (is_error_reported()) {
1287       // A fatal error has happened, the error handler(VMError::report_and_die)
1288       // should abort JVM after creating an error log file. However in some
1289       // rare cases, the error handler itself might deadlock. Here we try to
1290       // kill JVM if the fatal error handler fails to abort in 2 minutes.
1291       //


1458     set_thread_profiler(pp);
1459   }
1460 
1461   // Setup safepoint state info for this thread
1462   ThreadSafepointState::create(this);
1463 
1464   debug_only(_java_call_counter = 0);
1465 
1466   // JVMTI PopFrame support
1467   _popframe_condition = popframe_inactive;
1468   _popframe_preserved_args = NULL;
1469   _popframe_preserved_args_size = 0;
1470   _frames_to_pop_failed_realloc = 0;
1471 
1472   pd_initialize();
1473 }
1474 
1475 #if INCLUDE_ALL_GCS
1476 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
1477 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
1478 bool JavaThread::_evacuation_in_progress_global = false;
1479 #endif // INCLUDE_ALL_GCS
1480 
1481 JavaThread::JavaThread(bool is_attaching_via_jni) :
1482                        Thread()
1483 #if INCLUDE_ALL_GCS
1484                        , _satb_mark_queue(&_satb_mark_queue_set),
1485                        _dirty_card_queue(&_dirty_card_queue_set),
1486                        _evacuation_in_progress(_evacuation_in_progress_global)
1487 #endif // INCLUDE_ALL_GCS
1488 {
1489   initialize();
1490   if (is_attaching_via_jni) {
1491     _jni_attach_state = _attaching_via_jni;
1492   } else {
1493     _jni_attach_state = _not_attaching_via_jni;
1494   }
1495   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1496 }
1497 
1498 bool JavaThread::reguard_stack(address cur_sp) {
1499   if (_stack_guard_state != stack_guard_yellow_disabled) {
1500     return true; // Stack already guarded or guard pages not needed.
1501   }
1502 
1503   if (register_stack_overflow()) {
1504     // For those architectures which have separate register and
1505     // memory stacks, we must check the register stack to see if
1506     // it has overflowed.


1524 
1525 
1526 void JavaThread::block_if_vm_exited() {
1527   if (_terminated == _vm_exited) {
1528     // _vm_exited is set at safepoint, and Threads_lock is never released
1529     // we will block here forever
1530     Threads_lock->lock_without_safepoint_check();
1531     ShouldNotReachHere();
1532   }
1533 }
1534 
1535 
1536 // Remove this ifdef when C1 is ported to the compiler interface.
1537 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1538 static void sweeper_thread_entry(JavaThread* thread, TRAPS);
1539 
1540 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1541                        Thread()
1542 #if INCLUDE_ALL_GCS
1543                        , _satb_mark_queue(&_satb_mark_queue_set),
1544                        _dirty_card_queue(&_dirty_card_queue_set),
1545                        _evacuation_in_progress(_evacuation_in_progress_global)
1546 #endif // INCLUDE_ALL_GCS
1547 {
1548   initialize();
1549   _jni_attach_state = _not_attaching_via_jni;
1550   set_entry_point(entry_point);
1551   // Create the native thread itself.
1552   // %note runtime_23
1553   os::ThreadType thr_type = os::java_thread;
1554   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1555                                                      os::java_thread;
1556   os::create_thread(this, thr_type, stack_sz);
1557   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1558   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1559   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1560   // the exception consists of creating the exception object & initializing it, initialization
1561   // will leave the VM via a JavaCall and then all locks must be unlocked).
1562   //
1563   // The thread is still suspended when we reach here. Thread must be explicit started
1564   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1565   // by calling Threads:add. The reason why this is not done here, is because the thread


1660   // Note: Due to JVM_StopThread we can have pending exceptions already!
1661   if (!this->has_pending_exception() &&
1662       !java_lang_Thread::is_stillborn(this->threadObj())) {
1663     {
1664       ResourceMark rm(this);
1665       this->set_native_thread_name(this->get_thread_name());
1666     }
1667     HandleMark hm(this);
1668     this->entry_point()(this, this);
1669   }
1670 
1671   DTRACE_THREAD_PROBE(stop, this);
1672 
1673   this->exit(false);
1674   delete this;
1675 }
1676 
1677 
1678 static void ensure_join(JavaThread* thread) {
1679   // We do not need to grap the Threads_lock, since we are operating on ourself.
1680   Handle threadObj(thread, oopDesc::bs()->write_barrier(thread->threadObj()));
1681   assert(threadObj.not_null(), "java thread object must exist");
1682   ObjectLocker lock(threadObj, thread);
1683   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1684   thread->clear_pending_exception();
1685   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1686   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1687   // Clear the native thread instance - this makes isAlive return false and allows the join()
1688   // to complete once we've done the notify_all below
1689   java_lang_Thread::set_thread(threadObj(), NULL);
1690   lock.notify_all(thread);
1691   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1692   thread->clear_pending_exception();
1693 }
1694 
1695 
1696 // For any new cleanup additions, please check to see if they need to be applied to
1697 // cleanup_failed_attach_current_thread as well.
1698 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1699   assert(this == JavaThread::current(), "thread consistency check");
1700 


1854   remove_stack_guard_pages();
1855 
1856   if (UseTLAB) {
1857     tlab().make_parsable(true);  // retire TLAB
1858   }
1859 
1860   if (JvmtiEnv::environments_might_exist()) {
1861     JvmtiExport::cleanup_thread(this);
1862   }
1863 
1864   // We must flush any deferred card marks before removing a thread from
1865   // the list of active threads.
1866   Universe::heap()->flush_deferred_store_barrier(this);
1867   assert(deferred_card_mark().is_empty(), "Should have been flushed");
1868 
1869 #if INCLUDE_ALL_GCS
1870   // We must flush the G1-related buffers before removing a thread
1871   // from the list of active threads. We must do this after any deferred
1872   // card marks have been flushed (above) so that any entries that are
1873   // added to the thread's dirty card queue as a result are not lost.
1874   if (UseG1GC || UseShenandoahGC) {
1875     flush_barrier_queues();
1876   }
1877   if (UseShenandoahGC && UseTLAB) {
1878     gclab().make_parsable(true);
1879   }
1880 #endif // INCLUDE_ALL_GCS
1881 
1882   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1883   Threads::remove(this);
1884 }
1885 
1886 #if INCLUDE_ALL_GCS
1887 // Flush G1-related queues.
1888 void JavaThread::flush_barrier_queues() {
1889   satb_mark_queue().flush();
1890   dirty_card_queue().flush();
1891 }
1892 
1893 void JavaThread::initialize_queues() {
1894   assert(!SafepointSynchronize::is_at_safepoint(),
1895          "we should not be at a safepoint");
1896 
1897   ObjPtrQueue& satb_queue = satb_mark_queue();
1898   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
1899   // The SATB queue should have been constructed with its active
1900   // field set to false.
1901   assert(!satb_queue.is_active(), "SATB queue should not be active");
1902   assert(satb_queue.is_empty(), "SATB queue should be empty");
1903   // If we are creating the thread during a marking cycle, we should
1904   // set the active field of the SATB queue to true.
1905   if (satb_queue_set.is_active()) {
1906     satb_queue.set_active(true);
1907   }
1908 
1909   DirtyCardQueue& dirty_queue = dirty_card_queue();
1910   // The dirty card queue should have been constructed with its
1911   // active field set to true.
1912   assert(dirty_queue.is_active(), "dirty card queue should be active");
1913 }
1914 
1915 bool JavaThread::evacuation_in_progress() const {
1916   return _evacuation_in_progress;
1917 }
1918 
1919 void JavaThread::set_evacuation_in_progress(bool in_prog) {
1920   _evacuation_in_progress = in_prog;
1921 }
1922 
1923 void JavaThread::set_evacuation_in_progress_all_threads(bool in_prog) {
1924   _evacuation_in_progress_global = in_prog;
1925   for (JavaThread* t = Threads::first(); t; t = t->next()) {
1926     t->set_evacuation_in_progress(in_prog);
1927   }
1928 }
1929 #endif // INCLUDE_ALL_GCS
1930 
1931 void JavaThread::cleanup_failed_attach_current_thread() {
1932   if (get_thread_profiler() != NULL) {
1933     get_thread_profiler()->disengage();
1934     ResourceMark rm;
1935     get_thread_profiler()->print(get_thread_name());
1936   }
1937 
1938   if (active_handles() != NULL) {
1939     JNIHandleBlock* block = active_handles();
1940     set_active_handles(NULL);
1941     JNIHandleBlock::release_block(block);
1942   }
1943 
1944   if (free_handle_block() != NULL) {
1945     JNIHandleBlock* block = free_handle_block();
1946     set_free_handle_block(NULL);
1947     JNIHandleBlock::release_block(block);
1948   }
1949 
1950   // These have to be removed while this is still a valid thread.
1951   remove_stack_guard_pages();
1952 
1953   if (UseTLAB) {
1954     tlab().make_parsable(true);  // retire TLAB, if any
1955   }
1956 
1957 #if INCLUDE_ALL_GCS
1958   if (UseG1GC || UseShenandoahGC) {
1959     flush_barrier_queues();
1960   }
1961   if (UseShenandoahGC && UseTLAB) {
1962     gclab().make_parsable(true);
1963   }
1964 #endif // INCLUDE_ALL_GCS
1965 
1966   Threads::remove(this);
1967   delete this;
1968 }
1969 
1970 
1971 
1972 
1973 JavaThread* JavaThread::active() {
1974   Thread* thread = ThreadLocalStorage::thread();
1975   assert(thread != NULL, "just checking");
1976   if (thread->is_Java_thread()) {
1977     return (JavaThread*) thread;
1978   } else {
1979     assert(thread->is_VM_thread(), "this must be a vm thread");
1980     VM_Operation* op = ((VMThread*) thread)->vm_operation();
1981     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
1982     assert(ret->is_Java_thread(), "must be a Java thread");
1983     return ret;


2892     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2893       name_str = "<no-name - thread is attaching>";
2894     } else {
2895       name_str = Thread::name();
2896     }
2897   } else {
2898     name_str = Thread::name();
2899   }
2900   assert(name_str != NULL, "unexpected NULL thread name");
2901   return name_str;
2902 }
2903 
2904 
2905 const char* JavaThread::get_threadgroup_name() const {
2906   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2907   oop thread_obj = threadObj();
2908   if (thread_obj != NULL) {
2909     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2910     if (thread_group != NULL) {
2911       typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
2912       name = typeArrayOop(oopDesc::bs()->read_barrier(name));
2913       // ThreadGroup.name can be null
2914       if (name != NULL) {
2915         const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2916         return str;
2917       }
2918     }
2919   }
2920   return NULL;
2921 }
2922 
2923 const char* JavaThread::get_parent_name() const {
2924   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
2925   oop thread_obj = threadObj();
2926   if (thread_obj != NULL) {
2927     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
2928     if (thread_group != NULL) {
2929       oop parent = java_lang_ThreadGroup::parent(thread_group);
2930       if (parent != NULL) {
2931         typeArrayOop name = java_lang_ThreadGroup::name(parent);
2932         name = typeArrayOop(oopDesc::bs()->read_barrier(name));
2933         // ThreadGroup.name can be null
2934         if (name != NULL) {
2935           const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
2936           return str;
2937         }
2938       }
2939     }
2940   }
2941   return NULL;
2942 }
2943 
2944 ThreadPriority JavaThread::java_priority() const {
2945   oop thr_oop = threadObj();
2946   if (thr_oop == NULL) return NormPriority; // Bootstrapping
2947   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
2948   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
2949   return priority;
2950 }
2951 
2952 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {


3525   Metaspace::post_initialize();
3526 
3527   HOTSPOT_VM_INIT_END();
3528 
3529   // record VM initialization completion time
3530 #if INCLUDE_MANAGEMENT
3531   Management::record_vm_init_completed();
3532 #endif // INCLUDE_MANAGEMENT
3533 
3534   // Compute system loader. Note that this has to occur after set_init_completed, since
3535   // valid exceptions may be thrown in the process.
3536   // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
3537   // set_init_completed has just been called, causing exceptions not to be shortcut
3538   // anymore. We call vm_exit_during_initialization directly instead.
3539   SystemDictionary::compute_java_system_loader(CHECK_JNI_ERR);
3540 
3541 #if INCLUDE_ALL_GCS
3542   // Support for ConcurrentMarkSweep. This should be cleaned up
3543   // and better encapsulated. The ugly nested if test would go away
3544   // once things are properly refactored. XXX YSR
3545   if (UseConcMarkSweepGC || UseG1GC || UseShenandoahGC) {
3546     if (UseConcMarkSweepGC) {
3547       ConcurrentMarkSweepThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3548     } else if (UseShenandoahGC) {
3549       ShenandoahConcurrentThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3550     } else {
3551       ConcurrentMarkThread::makeSurrogateLockerThread(CHECK_JNI_ERR);
3552     }
3553   }
3554 #endif // INCLUDE_ALL_GCS
3555 
3556   // Always call even when there are not JVMTI environments yet, since environments
3557   // may be attached late and JVMTI must track phases of VM execution
3558   JvmtiExport::enter_live_phase();
3559 
3560   // Signal Dispatcher needs to be started before VMInit event is posted
3561   os::signal_init();
3562 
3563   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3564   if (!DisableAttachMechanism) {
3565     AttachListener::vm_start();
3566     if (StartAttachListener || AttachListener::init_at_startup()) {
3567       AttachListener::init();
3568     }
3569   }


3937       // complete. wait_for_ext_suspend_completion() will eventually
3938       // timeout, but that takes time. Making this wait a suspend-
3939       // equivalent condition solves that timeout problem.
3940       //
3941       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
3942                          Mutex::_as_suspend_equivalent_flag);
3943   }
3944 
3945   // Hang forever on exit if we are reporting an error.
3946   if (ShowMessageBoxOnError && is_error_reported()) {
3947     os::infinite_sleep();
3948   }
3949   os::wait_for_keypress_at_exit();
3950 
3951   // run Java level shutdown hooks
3952   thread->invoke_shutdown_hooks();
3953 
3954   before_exit(thread);
3955 
3956   thread->exit(true);
3957 
3958   // Stop GC threads.
3959   Universe::heap()->shutdown();
3960 
3961   // Stop VM thread.
3962   {
3963     // 4945125 The vm thread comes to a safepoint during exit.
3964     // GC vm_operations can get caught at the safepoint, and the
3965     // heap is unparseable if they are caught. Grab the Heap_lock
3966     // to prevent this. The GC vm_operations will not be able to
3967     // queue until after the vm thread is dead. After this point,
3968     // we'll never emerge out of the safepoint before the VM exits.
3969 
3970     MutexLocker ml(Heap_lock);
3971 
3972     VMThread::wait_for_vm_thread_exit();
3973     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
3974     VMThread::destroy();
3975   }
3976 
3977   // clean up ideal graph printers
3978 #if defined(COMPILER2) && !defined(PRODUCT)
3979   IdealGraphPrinter::clean_up();


< prev index next >