mutexLocker.hpp revision 1879:f95d63e2154a
1/*
2 * Copyright (c) 1997, 2010, 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 *
23 */
24
25#ifndef SHARE_VM_RUNTIME_MUTEXLOCKER_HPP
26#define SHARE_VM_RUNTIME_MUTEXLOCKER_HPP
27
28#include "memory/allocation.hpp"
29#include "runtime/mutex.hpp"
30#ifdef TARGET_OS_FAMILY_linux
31# include "os_linux.inline.hpp"
32#endif
33#ifdef TARGET_OS_FAMILY_solaris
34# include "os_solaris.inline.hpp"
35#endif
36#ifdef TARGET_OS_FAMILY_windows
37# include "os_windows.inline.hpp"
38#endif
39
40// Mutexes used in the VM.
41
42extern Mutex*   Patching_lock;                   // a lock used to guard code patching of compiled code
43extern Monitor* SystemDictionary_lock;           // a lock on the system dictonary
44extern Mutex*   PackageTable_lock;               // a lock on the class loader package table
45extern Mutex*   CompiledIC_lock;                 // a lock used to guard compiled IC patching and access
46extern Mutex*   InlineCacheBuffer_lock;          // a lock used to guard the InlineCacheBuffer
47extern Mutex*   VMStatistic_lock;                // a lock used to guard statistics count increment
48extern Mutex*   JNIGlobalHandle_lock;            // a lock on creating JNI global handles
49extern Mutex*   JNIHandleBlockFreeList_lock;     // a lock on the JNI handle block free list
50extern Mutex*   JNICachedItableIndex_lock;       // a lock on caching an itable index during JNI invoke
51extern Mutex*   JmethodIdCreation_lock;          // a lock on creating JNI method identifiers
52extern Mutex*   JfieldIdCreation_lock;           // a lock on creating JNI static field identifiers
53extern Monitor* JNICritical_lock;                // a lock used while entering and exiting JNI critical regions, allows GC to sometimes get in
54extern Mutex*   JvmtiThreadState_lock;           // a lock on modification of JVMTI thread data
55extern Monitor* JvmtiPendingEvent_lock;          // a lock on the JVMTI pending events list
56extern Monitor* Heap_lock;                       // a lock on the heap
57extern Mutex*   ExpandHeap_lock;                 // a lock on expanding the heap
58extern Mutex*   AdapterHandlerLibrary_lock;      // a lock on the AdapterHandlerLibrary
59extern Mutex*   SignatureHandlerLibrary_lock;    // a lock on the SignatureHandlerLibrary
60extern Mutex*   VtableStubs_lock;                // a lock on the VtableStubs
61extern Mutex*   SymbolTable_lock;                // a lock on the symbol table
62extern Mutex*   StringTable_lock;                // a lock on the interned string table
63extern Mutex*   CodeCache_lock;                  // a lock on the CodeCache, rank is special, use MutexLockerEx
64extern Mutex*   MethodData_lock;                 // a lock on installation of method data
65extern Mutex*   RetData_lock;                    // a lock on installation of RetData inside method data
66extern Mutex*   DerivedPointerTableGC_lock;      // a lock to protect the derived pointer table
67extern Monitor* VMOperationQueue_lock;           // a lock on queue of vm_operations waiting to execute
68extern Monitor* VMOperationRequest_lock;         // a lock on Threads waiting for a vm_operation to terminate
69extern Monitor* Safepoint_lock;                  // a lock used by the safepoint abstraction
70extern Monitor* Threads_lock;                    // a lock on the Threads table of active Java threads
71                                                 // (also used by Safepoints too to block threads creation/destruction)
72extern Monitor* CGC_lock;                        // used for coordination between
73                                                 // fore- & background GC threads.
74extern Mutex*   STS_init_lock;                   // coordinate initialization of SuspendibleThreadSets.
75extern Monitor* SLT_lock;                        // used in CMS GC for acquiring PLL
76extern Monitor* iCMS_lock;                       // CMS incremental mode start/stop notification
77extern Monitor* FullGCCount_lock;                // in support of "concurrent" full gc
78extern Monitor* CMark_lock;                      // used for concurrent mark thread coordination
79extern Monitor* ZF_mon;                          // used for G1 conc zero-fill.
80extern Monitor* Cleanup_mon;                     // used for G1 conc cleanup.
81extern Mutex*   CMRegionStack_lock;              // used for protecting accesses to the CM region stack
82extern Mutex*   SATB_Q_FL_lock;                  // Protects SATB Q
83                                                 // buffer free list.
84extern Monitor* SATB_Q_CBL_mon;                  // Protects SATB Q
85                                                 // completed buffer queue.
86extern Mutex*   Shared_SATB_Q_lock;              // Lock protecting SATB
87                                                 // queue shared by
88                                                 // non-Java threads.
89
90extern Mutex*   DirtyCardQ_FL_lock;              // Protects dirty card Q
91                                                 // buffer free list.
92extern Monitor* DirtyCardQ_CBL_mon;              // Protects dirty card Q
93                                                 // completed buffer queue.
94extern Mutex*   Shared_DirtyCardQ_lock;          // Lock protecting dirty card
95                                                 // queue shared by
96                                                 // non-Java threads.
97                                                 // (see option ExplicitGCInvokesConcurrent)
98extern Mutex*   ParGCRareEvent_lock;             // Synchronizes various (rare) parallel GC ops.
99extern Mutex*   EvacFailureStack_lock;           // guards the evac failure scan stack
100extern Mutex*   Compile_lock;                    // a lock held when Compilation is updating code (used to block CodeCache traversal, CHA updates, etc)
101extern Monitor* MethodCompileQueue_lock;         // a lock held when method compilations are enqueued, dequeued
102extern Monitor* CompileThread_lock;              // a lock held by compile threads during compilation system initialization
103extern Mutex*   CompileTaskAlloc_lock;           // a lock held when CompileTasks are allocated
104extern Mutex*   CompileStatistics_lock;          // a lock held when updating compilation statistics
105extern Mutex*   MultiArray_lock;                 // a lock used to guard allocation of multi-dim arrays
106extern Monitor* Terminator_lock;                 // a lock used to guard termination of the vm
107extern Monitor* BeforeExit_lock;                 // a lock used to guard cleanups and shutdown hooks
108extern Monitor* Notify_lock;                     // a lock used to synchronize the start-up of the vm
109extern Monitor* Interrupt_lock;                  // a lock used for condition variable mediated interrupt processing
110extern Monitor* ProfileVM_lock;                  // a lock used for profiling the VMThread
111extern Mutex*   ProfilePrint_lock;               // a lock used to serialize the printing of profiles
112extern Mutex*   ExceptionCache_lock;             // a lock used to synchronize exception cache updates
113extern Mutex*   OsrList_lock;                    // a lock used to serialize access to OSR queues
114
115#ifndef PRODUCT
116extern Mutex*   FullGCALot_lock;                 // a lock to make FullGCALot MT safe
117#endif
118extern Mutex*   Debug1_lock;                     // A bunch of pre-allocated locks that can be used for tracing
119extern Mutex*   Debug2_lock;                     // down synchronization related bugs!
120extern Mutex*   Debug3_lock;
121
122extern Mutex*   RawMonitor_lock;
123extern Mutex*   PerfDataMemAlloc_lock;           // a lock on the allocator for PerfData memory for performance data
124extern Mutex*   PerfDataManager_lock;            // a long on access to PerfDataManager resources
125extern Mutex*   ParkerFreeList_lock;
126extern Mutex*   OopMapCacheAlloc_lock;           // protects allocation of oop_map caches
127
128extern Mutex*   MMUTracker_lock;                 // protects the MMU
129                                                 // tracker data structures
130extern Mutex*   HotCardCache_lock;               // protects the hot card cache
131
132extern Mutex*   Management_lock;                 // a lock used to serialize JVM management
133extern Monitor* LowMemory_lock;                  // a lock used for low memory detection
134
135// A MutexLocker provides mutual exclusion with respect to a given mutex
136// for the scope which contains the locker.  The lock is an OS lock, not
137// an object lock, and the two do not interoperate.  Do not use Mutex-based
138// locks to lock on Java objects, because they will not be respected if a
139// that object is locked using the Java locking mechanism.
140//
141//                NOTE WELL!!
142//
143// See orderAccess.hpp.  We assume throughout the VM that MutexLocker's
144// and friends constructors do a fence, a lock and an acquire *in that
145// order*.  And that their destructors do a release and unlock, in *that*
146// order.  If their implementations change such that these assumptions
147// are violated, a whole lot of code will break.
148
149// Print all mutexes/monitors that are currently owned by a thread; called
150// by fatal error handler.
151void print_owned_locks_on_error(outputStream* st);
152
153char *lock_name(Mutex *mutex);
154
155class MutexLocker: StackObj {
156 private:
157  Monitor * _mutex;
158 public:
159  MutexLocker(Monitor * mutex) {
160    assert(mutex->rank() != Mutex::special,
161      "Special ranked mutex should only use MutexLockerEx");
162    _mutex = mutex;
163    _mutex->lock();
164  }
165
166  // Overloaded constructor passing current thread
167  MutexLocker(Monitor * mutex, Thread *thread) {
168    assert(mutex->rank() != Mutex::special,
169      "Special ranked mutex should only use MutexLockerEx");
170    _mutex = mutex;
171    _mutex->lock(thread);
172  }
173
174  ~MutexLocker() {
175    _mutex->unlock();
176  }
177
178};
179
180// for debugging: check that we're already owning this lock (or are at a safepoint)
181#ifdef ASSERT
182void assert_locked_or_safepoint(const Monitor * lock);
183void assert_lock_strong(const Monitor * lock);
184#else
185#define assert_locked_or_safepoint(lock)
186#define assert_lock_strong(lock)
187#endif
188
189// A MutexLockerEx behaves like a MutexLocker when its constructor is
190// called with a Mutex.  Unlike a MutexLocker, its constructor can also be
191// called with NULL, in which case the MutexLockerEx is a no-op.  There
192// is also a corresponding MutexUnlockerEx.  We want to keep the
193// basic MutexLocker as fast as possible.  MutexLockerEx can also lock
194// without safepoint check.
195
196class MutexLockerEx: public StackObj {
197 private:
198  Monitor * _mutex;
199 public:
200  MutexLockerEx(Monitor * mutex, bool no_safepoint_check = !Mutex::_no_safepoint_check_flag) {
201    _mutex = mutex;
202    if (_mutex != NULL) {
203      assert(mutex->rank() > Mutex::special || no_safepoint_check,
204        "Mutexes with rank special or lower should not do safepoint checks");
205      if (no_safepoint_check)
206        _mutex->lock_without_safepoint_check();
207      else
208        _mutex->lock();
209    }
210  }
211
212  ~MutexLockerEx() {
213    if (_mutex != NULL) {
214      _mutex->unlock();
215    }
216  }
217};
218
219// A MonitorLockerEx is like a MutexLockerEx above, except it takes
220// a possibly null Monitor, and allows wait/notify as well which are
221// delegated to the underlying Monitor.
222
223class MonitorLockerEx: public MutexLockerEx {
224 private:
225  Monitor * _monitor;
226 public:
227  MonitorLockerEx(Monitor* monitor,
228                  bool no_safepoint_check = !Mutex::_no_safepoint_check_flag):
229    MutexLockerEx(monitor, no_safepoint_check),
230    _monitor(monitor) {
231    // Superclass constructor did locking
232  }
233
234  ~MonitorLockerEx() {
235    #ifdef ASSERT
236      if (_monitor != NULL) {
237        assert_lock_strong(_monitor);
238      }
239    #endif  // ASSERT
240    // Superclass destructor will do unlocking
241  }
242
243  bool wait(bool no_safepoint_check = !Mutex::_no_safepoint_check_flag,
244            long timeout = 0,
245            bool as_suspend_equivalent = !Mutex::_as_suspend_equivalent_flag) {
246    if (_monitor != NULL) {
247      return _monitor->wait(no_safepoint_check, timeout, as_suspend_equivalent);
248    }
249    return false;
250  }
251
252  bool notify_all() {
253    if (_monitor != NULL) {
254      return _monitor->notify_all();
255    }
256    return true;
257  }
258
259  bool notify() {
260    if (_monitor != NULL) {
261      return _monitor->notify();
262    }
263    return true;
264  }
265};
266
267
268
269// A GCMutexLocker is usually initialized with a mutex that is
270// automatically acquired in order to do GC.  The function that
271// synchronizes using a GCMutexLocker may be called both during and between
272// GC's.  Thus, it must acquire the mutex if GC is not in progress, but not
273// if GC is in progress (since the mutex is already held on its behalf.)
274
275class GCMutexLocker: public StackObj {
276private:
277  Monitor * _mutex;
278  bool _locked;
279public:
280  GCMutexLocker(Monitor * mutex);
281  ~GCMutexLocker() { if (_locked) _mutex->unlock(); }
282};
283
284
285
286// A MutexUnlocker temporarily exits a previously
287// entered mutex for the scope which contains the unlocker.
288
289class MutexUnlocker: StackObj {
290 private:
291  Monitor * _mutex;
292
293 public:
294  MutexUnlocker(Monitor * mutex) {
295    _mutex = mutex;
296    _mutex->unlock();
297  }
298
299  ~MutexUnlocker() {
300    _mutex->lock();
301  }
302};
303
304// A MutexUnlockerEx temporarily exits a previously
305// entered mutex for the scope which contains the unlocker.
306
307class MutexUnlockerEx: StackObj {
308 private:
309  Monitor * _mutex;
310  bool _no_safepoint_check;
311
312 public:
313  MutexUnlockerEx(Monitor * mutex, bool no_safepoint_check = !Mutex::_no_safepoint_check_flag) {
314    _mutex = mutex;
315    _no_safepoint_check = no_safepoint_check;
316    _mutex->unlock();
317  }
318
319  ~MutexUnlockerEx() {
320    if (_no_safepoint_check == Mutex::_no_safepoint_check_flag) {
321      _mutex->lock_without_safepoint_check();
322    } else {
323      _mutex->lock();
324    }
325  }
326};
327
328#ifndef PRODUCT
329//
330// A special MutexLocker that allows:
331//   - reentrant locking
332//   - locking out of order
333//
334// Only too be used for verify code, where we can relaxe out dead-lock
335// dection code a bit (unsafe, but probably ok). This code is NEVER to
336// be included in a product version.
337//
338class VerifyMutexLocker: StackObj {
339 private:
340  Monitor * _mutex;
341  bool   _reentrant;
342 public:
343  VerifyMutexLocker(Monitor * mutex) {
344    _mutex     = mutex;
345    _reentrant = mutex->owned_by_self();
346    if (!_reentrant) {
347      // We temp. diable strict safepoint checking, while we require the lock
348      FlagSetting fs(StrictSafepointChecks, false);
349      _mutex->lock();
350    }
351  }
352
353  ~VerifyMutexLocker() {
354    if (!_reentrant) {
355      _mutex->unlock();
356    }
357  }
358};
359
360#endif
361
362#endif // SHARE_VM_RUNTIME_MUTEXLOCKER_HPP
363