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