src/share/vm/runtime/thread.cpp

Print this page


   1 /*
   2  * Copyright (c) 1997, 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  *


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


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





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

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





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


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


   1 /*
   2  * Copyright (c) 1997, 2015, 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  *


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


1338     _should_terminate = true;
1339     OrderAccess::fence();  // ensure WatcherThread sees update in main loop
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" {