src/share/vm/runtime/thread.cpp

Print this page




1180 
1181 WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
1182   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1183   if (os::create_thread(this, os::watcher_thread)) {
1184     _watcher_thread = this;
1185 
1186     // Set the watcher thread to the highest OS priority which should not be
1187     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1188     // is created. The only normal thread using this priority is the reference
1189     // handler thread, which runs for very short intervals only.
1190     // If the VMThread's priority is not lower than the WatcherThread profiling
1191     // will be inaccurate.
1192     os::set_priority(this, MaxPriority);
1193     if (!DisableStartThread) {
1194       os::start_thread(this);
1195     }
1196   }
1197 }
1198 
1199 int WatcherThread::sleep() const {


1200   MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1201 





1202   // remaining will be zero if there are no tasks,
1203   // causing the WatcherThread to sleep until a task is
1204   // enrolled
1205   int remaining = PeriodicTask::time_to_wait();
1206   int time_slept = 0;
1207 
1208   // we expect this to timeout - we only ever get unparked when
1209   // we should terminate or when a new task has been enrolled
1210   OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1211 
1212   jlong time_before_loop = os::javaTimeNanos();
1213 
1214   for (;;) {
1215     bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining);

1216     jlong now = os::javaTimeNanos();
1217 
1218     if (remaining == 0) {
1219       // if we didn't have any tasks we could have waited for a long time
1220       // consider the time_slept zero and reset time_before_loop
1221       time_slept = 0;
1222       time_before_loop = now;
1223     } else {
1224       // need to recalculate since we might have new tasks in _tasks
1225       time_slept = (int) ((now - time_before_loop) / 1000000);
1226     }
1227 
1228     // Change to task list or spurious wakeup of some kind
1229     if (timedout || _should_terminate) {
1230       break;
1231     }
1232 
1233     remaining = PeriodicTask::time_to_wait();
1234     if (remaining == 0) {
1235       // Last task was just disenrolled so loop around and wait until
1236       // another task gets enrolled
1237       continue;
1238     }
1239 
1240     remaining -= time_slept;
1241     if (remaining <= 0) {
1242       break;
1243     }
1244   }
1245 
1246   return time_slept;
1247 }
1248 
1249 void WatcherThread::run() {
1250   assert(this == watcher_thread(), "just checking");
1251 
1252   this->record_stack_base_and_size();
1253   this->initialize_thread_local_storage();
1254   this->set_native_thread_name(this->name());
1255   this->set_active_handles(JNIHandleBlock::allocate_block());
1256   while (!_should_terminate) {
1257     assert(watcher_thread() == Thread::current(), "thread consistency check");
1258     assert(watcher_thread() == this, "thread consistency check");
1259 
1260     // Calculate how long it'll be until the next PeriodicTask work
1261     // should be done, and sleep that amount of time.
1262     int time_waited = sleep();
1263 
1264     if (is_error_reported()) {
1265       // A fatal error has happened, the error handler(VMError::report_and_die)
1266       // should abort JVM after creating an error log file. However in some
1267       // rare cases, the error handler itself might deadlock. Here we try to
1268       // kill JVM if the fatal error handler fails to abort in 2 minutes.
1269       //
1270       // This code is in WatcherThread because WatcherThread wakes up
1271       // periodically so the fatal error handler doesn't need to do anything;
1272       // also because the WatcherThread is less likely to crash than other
1273       // threads.
1274 
1275       for (;;) {
1276         if (!ShowMessageBoxOnError
1277             && (OnError == NULL || OnError[0] == '\0')
1278             && Arguments::abort_hook() == NULL) {
1279           os::sleep(this, 2 * 60 * 1000, false);
1280           fdStream err(defaultStream::output_fd());
1281           err.print_raw_cr("# [ timer expired, abort... ]");
1282           // skip atexit/vm_exit/vm_abort hooks
1283           os::die();
1284         }
1285 
1286         // Wake up 5 seconds later, the fatal handler may reset OnError or
1287         // ShowMessageBoxOnError when it is ready to abort.
1288         os::sleep(this, 5 * 1000, false);
1289       }
1290     }
1291 





1292     PeriodicTask::real_time_tick(time_waited);
1293   }
1294 
1295   // Signal that it is terminated
1296   {
1297     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1298     _watcher_thread = NULL;
1299     Terminator_lock->notify();
1300   }
1301 
1302   // Thread destructor usually does this..
1303   ThreadLocalStorage::set_thread(NULL);
1304 }
1305 
1306 void WatcherThread::start() {
1307   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1308 
1309   if (watcher_thread() == NULL && _startable) {
1310     _should_terminate = false;
1311     // Create the single instance of WatcherThread
1312     new WatcherThread();
1313   }
1314 }
1315 
1316 void WatcherThread::make_startable() {
1317   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1318   _startable = true;
1319 }
1320 
1321 void WatcherThread::stop() {
1322   // Get the PeriodicTask_lock if we can. If we cannot, then the
1323   // WatcherThread is using it and we don't want to block on that lock
1324   // here because that might cause a safepoint deadlock depending on
1325   // what the current WatcherThread tasks are doing.
1326   bool have_lock = PeriodicTask_lock->try_lock();
1327 
1328   _should_terminate = true;
1329   OrderAccess::fence();  // ensure WatcherThread sees update in main loop
1330 
1331   if (have_lock) {
1332     WatcherThread* watcher = watcher_thread();
1333     if (watcher != NULL) {
1334       // If we managed to get the lock, then we should unpark the
1335       // WatcherThread so that it can see we want it to stop.
1336       watcher->unpark();
1337     }
1338 
1339     PeriodicTask_lock->unlock();
1340   }
1341 
1342   // it is ok to take late safepoints here, if needed
1343   MutexLocker mu(Terminator_lock);
1344 
1345   while (watcher_thread() != NULL) {
1346     // This wait should make safepoint checks, wait without a timeout,
1347     // and wait as a suspend-equivalent condition.
1348     //
1349     // Note: If the FlatProfiler is running, then this thread is waiting
1350     // for the WatcherThread to terminate and the WatcherThread, via the
1351     // FlatProfiler task, is waiting for the external suspend request on
1352     // this thread to complete. wait_for_ext_suspend_completion() will
1353     // eventually timeout, but that takes time. Making this wait a
1354     // suspend-equivalent condition solves that timeout problem.
1355     //
1356     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1357                           Mutex::_as_suspend_equivalent_flag);
1358   }
1359 }
1360 
1361 void WatcherThread::unpark() {
1362   MutexLockerEx ml(PeriodicTask_lock->owned_by_self()
1363                    ? NULL
1364                    : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1365   PeriodicTask_lock->notify();
1366 }
1367 
1368 void WatcherThread::print_on(outputStream* st) const {
1369   st->print("\"%s\" ", name());
1370   Thread::print_on(st);
1371   st->cr();
1372 }
1373 
1374 // ======= JavaThread ========
1375 
1376 // A JavaThread is a normal Java thread
1377 
1378 void JavaThread::initialize() {
1379   // Initialize fields
1380 
1381   // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1382   set_claimed_par_id(UINT_MAX);
1383 
1384   set_saved_exception_pc(NULL);


3541   if (MemProfiling)                   MemProfiler::engage();
3542   StatSampler::engage();
3543   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3544 
3545   BiasedLocking::init();
3546 
3547 #if INCLUDE_RTM_OPT
3548   RTMLockingCounters::init();
3549 #endif
3550 
3551   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3552     call_postVMInitHook(THREAD);
3553     // The Java side of PostVMInitHook.run must deal with all
3554     // exceptions and provide means of diagnosis.
3555     if (HAS_PENDING_EXCEPTION) {
3556       CLEAR_PENDING_EXCEPTION;
3557     }
3558   }
3559 
3560   {
3561     MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
3562     // Make sure the watcher thread can be started by WatcherThread::start()
3563     // or by dynamic enrollment.
3564     WatcherThread::make_startable();
3565     // Start up the WatcherThread if there are any periodic tasks
3566     // NOTE:  All PeriodicTasks should be registered by now. If they
3567     //   aren't, late joiners might appear to start slowly (we might
3568     //   take a while to process their first tick).
3569     if (PeriodicTask::num_tasks() > 0) {
3570       WatcherThread::start();
3571     }
3572   }
3573 
3574   create_vm_timer.end();
3575 #ifdef ASSERT
3576   _vm_complete = true;
3577 #endif
3578   return JNI_OK;
3579 }
3580 
3581 // type for the Agent_OnLoad and JVM_OnLoad entry points
3582 extern "C" {




1180 
1181 WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
1182   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1183   if (os::create_thread(this, os::watcher_thread)) {
1184     _watcher_thread = this;
1185 
1186     // Set the watcher thread to the highest OS priority which should not be
1187     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1188     // is created. The only normal thread using this priority is the reference
1189     // handler thread, which runs for very short intervals only.
1190     // If the VMThread's priority is not lower than the WatcherThread profiling
1191     // will be inaccurate.
1192     os::set_priority(this, MaxPriority);
1193     if (!DisableStartThread) {
1194       os::start_thread(this);
1195     }
1196   }
1197 }
1198 
1199 int WatcherThread::sleep() const {
1200   // The WatcherThread is not a JavaThread so we do not honor the
1201   // safepoint protocol for the PeriodicTask_lock.
1202   MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1203 
1204   if (_should_terminate) {
1205     // check for termination before we do any housekeeping or wait
1206     return 0;  // we did not sleep.
1207   }
1208 
1209   // remaining will be zero if there are no tasks,
1210   // causing the WatcherThread to sleep until a task is
1211   // enrolled
1212   int remaining = PeriodicTask::time_to_wait();
1213   int time_slept = 0;
1214 
1215   // we expect this to timeout - we only ever get unparked when
1216   // we should terminate or when a new task has been enrolled
1217   OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1218 
1219   jlong time_before_loop = os::javaTimeNanos();
1220 
1221   while (true) {
1222     bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag,
1223                                             remaining);
1224     jlong now = os::javaTimeNanos();
1225 
1226     if (remaining == 0) {
1227       // if we didn't have any tasks we could have waited for a long time
1228       // consider the time_slept zero and reset time_before_loop
1229       time_slept = 0;
1230       time_before_loop = now;
1231     } else {
1232       // need to recalculate since we might have new tasks in _tasks
1233       time_slept = (int) ((now - time_before_loop) / 1000000);
1234     }
1235 
1236     // Change to task list or spurious wakeup of some kind
1237     if (timedout || _should_terminate) {
1238       break;
1239     }
1240 
1241     remaining = PeriodicTask::time_to_wait();
1242     if (remaining == 0) {
1243       // Last task was just disenrolled so loop around and wait until
1244       // another task gets enrolled
1245       continue;
1246     }
1247 
1248     remaining -= time_slept;
1249     if (remaining <= 0) {
1250       break;
1251     }
1252   }
1253 
1254   return time_slept;
1255 }
1256 
1257 void WatcherThread::run() {
1258   assert(this == watcher_thread(), "just checking");
1259 
1260   this->record_stack_base_and_size();
1261   this->initialize_thread_local_storage();
1262   this->set_native_thread_name(this->name());
1263   this->set_active_handles(JNIHandleBlock::allocate_block());
1264   while (true) {
1265     assert(watcher_thread() == Thread::current(), "thread consistency check");
1266     assert(watcher_thread() == this, "thread consistency check");
1267 
1268     // Calculate how long it'll be until the next PeriodicTask work
1269     // should be done, and sleep that amount of time.
1270     int time_waited = sleep();
1271 
1272     if (is_error_reported()) {
1273       // A fatal error has happened, the error handler(VMError::report_and_die)
1274       // should abort JVM after creating an error log file. However in some
1275       // rare cases, the error handler itself might deadlock. Here we try to
1276       // kill JVM if the fatal error handler fails to abort in 2 minutes.
1277       //
1278       // This code is in WatcherThread because WatcherThread wakes up
1279       // periodically so the fatal error handler doesn't need to do anything;
1280       // also because the WatcherThread is less likely to crash than other
1281       // threads.
1282 
1283       for (;;) {
1284         if (!ShowMessageBoxOnError
1285             && (OnError == NULL || OnError[0] == '\0')
1286             && Arguments::abort_hook() == NULL) {
1287           os::sleep(this, 2 * 60 * 1000, false);
1288           fdStream err(defaultStream::output_fd());
1289           err.print_raw_cr("# [ timer expired, abort... ]");
1290           // skip atexit/vm_exit/vm_abort hooks
1291           os::die();
1292         }
1293 
1294         // Wake up 5 seconds later, the fatal handler may reset OnError or
1295         // ShowMessageBoxOnError when it is ready to abort.
1296         os::sleep(this, 5 * 1000, false);
1297       }
1298     }
1299 
1300     if (_should_terminate) {
1301       // check for termination before posting the next tick
1302       break;
1303     }
1304 
1305     PeriodicTask::real_time_tick(time_waited);
1306   }
1307 
1308   // Signal that it is terminated
1309   {
1310     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1311     _watcher_thread = NULL;
1312     Terminator_lock->notify();
1313   }
1314 
1315   // Thread destructor usually does this..
1316   ThreadLocalStorage::set_thread(NULL);
1317 }
1318 
1319 void WatcherThread::start() {
1320   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1321 
1322   if (watcher_thread() == NULL && _startable) {
1323     _should_terminate = false;
1324     // Create the single instance of WatcherThread
1325     new WatcherThread();
1326   }
1327 }
1328 
1329 void WatcherThread::make_startable() {
1330   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1331   _startable = true;
1332 }
1333 
1334 void WatcherThread::stop() {
1335   {
1336     // Follow normal safepoint aware lock enter protocol since the
1337     // WatcherThread is stopped by another JavaThread.
1338     MutexLocker ml(PeriodicTask_lock);


1339     _should_terminate = true;

1340 

1341     WatcherThread* watcher = watcher_thread();
1342     if (watcher != NULL) {
1343       // unpark the WatcherThread so it can see that it should terminate

1344       watcher->unpark();
1345     }


1346   }
1347 

1348   MutexLocker mu(Terminator_lock);
1349 
1350   while (watcher_thread() != NULL) {
1351     // This wait should make safepoint checks, wait without a timeout,
1352     // and wait as a suspend-equivalent condition.
1353     //
1354     // Note: If the FlatProfiler is running, then this thread is waiting
1355     // for the WatcherThread to terminate and the WatcherThread, via the
1356     // FlatProfiler task, is waiting for the external suspend request on
1357     // this thread to complete. wait_for_ext_suspend_completion() will
1358     // eventually timeout, but that takes time. Making this wait a
1359     // suspend-equivalent condition solves that timeout problem.
1360     //
1361     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1362                           Mutex::_as_suspend_equivalent_flag);
1363   }
1364 }
1365 
1366 void WatcherThread::unpark() {
1367   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");


1368   PeriodicTask_lock->notify();
1369 }
1370 
1371 void WatcherThread::print_on(outputStream* st) const {
1372   st->print("\"%s\" ", name());
1373   Thread::print_on(st);
1374   st->cr();
1375 }
1376 
1377 // ======= JavaThread ========
1378 
1379 // A JavaThread is a normal Java thread
1380 
1381 void JavaThread::initialize() {
1382   // Initialize fields
1383 
1384   // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
1385   set_claimed_par_id(UINT_MAX);
1386 
1387   set_saved_exception_pc(NULL);


3544   if (MemProfiling)                   MemProfiler::engage();
3545   StatSampler::engage();
3546   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3547 
3548   BiasedLocking::init();
3549 
3550 #if INCLUDE_RTM_OPT
3551   RTMLockingCounters::init();
3552 #endif
3553 
3554   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3555     call_postVMInitHook(THREAD);
3556     // The Java side of PostVMInitHook.run must deal with all
3557     // exceptions and provide means of diagnosis.
3558     if (HAS_PENDING_EXCEPTION) {
3559       CLEAR_PENDING_EXCEPTION;
3560     }
3561   }
3562 
3563   {
3564     MutexLocker ml(PeriodicTask_lock);
3565     // Make sure the WatcherThread can be started by WatcherThread::start()
3566     // or by dynamic enrollment.
3567     WatcherThread::make_startable();
3568     // Start up the WatcherThread if there are any periodic tasks
3569     // NOTE:  All PeriodicTasks should be registered by now. If they
3570     //   aren't, late joiners might appear to start slowly (we might
3571     //   take a while to process their first tick).
3572     if (PeriodicTask::num_tasks() > 0) {
3573       WatcherThread::start();
3574     }
3575   }
3576 
3577   create_vm_timer.end();
3578 #ifdef ASSERT
3579   _vm_complete = true;
3580 #endif
3581   return JNI_OK;
3582 }
3583 
3584 // type for the Agent_OnLoad and JVM_OnLoad entry points
3585 extern "C" {