src/share/vm/runtime/mutex.hpp

Fri, 27 Feb 2009 13:27:09 -0800

author
twisti
date
Fri, 27 Feb 2009 13:27:09 -0800
changeset 1040
98cb887364d3
parent 631
d1605aabd0a1
child 1445
354d3184f6b2
permissions
-rw-r--r--

6810672: Comment typos
Summary: I have collected some typos I have found while looking at the code.
Reviewed-by: kvn, never

     1 /*
     2  * Copyright 1998-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  */
    25 // The SplitWord construct allows us to colocate the contention queue
    26 // (cxq) with the lock-byte.  The queue elements are ParkEvents, which are
    27 // always aligned on 256-byte addresses - the least significant byte of
    28 // a ParkEvent is always 0.  Colocating the lock-byte with the queue
    29 // allows us to easily avoid what would otherwise be a race in lock()
    30 // if we were to use two completely separate fields for the contention queue
    31 // and the lock indicator.  Specifically, colocation renders us immune
    32 // from the race where a thread might enqueue itself in the lock() slow-path
    33 // immediately after the lock holder drops the outer lock in the unlock()
    34 // fast-path.
    35 //
    36 // Colocation allows us to use a fast-path unlock() form that uses
    37 // A MEMBAR instead of a CAS.  MEMBAR has lower local latency than CAS
    38 // on many platforms.
    39 //
    40 // See:
    41 // +  http://blogs.sun.com/dave/entry/biased_locking_in_hotspot
    42 // +  http://blogs.sun.com/dave/resource/synchronization-public2.pdf
    43 //
    44 // Note that we're *not* using word-tearing the classic sense.
    45 // The lock() fast-path will CAS the lockword and the unlock()
    46 // fast-path will store into the lock-byte colocated within the lockword.
    47 // We depend on the fact that all our reference platforms have
    48 // coherent and atomic byte accesses.  More precisely, byte stores
    49 // interoperate in a safe, sane, and expected manner with respect to
    50 // CAS, ST and LDs to the full-word containing the byte.
    51 // If you're porting HotSpot to a platform where that isn't the case
    52 // then you'll want change the unlock() fast path from:
    53 //    STB;MEMBAR #storeload; LDN
    54 // to a full-word CAS of the lockword.
    57 union SplitWord {   // full-word with separately addressable LSB
    58   volatile intptr_t FullWord ;
    59   volatile void * Address ;
    60   volatile jbyte Bytes [sizeof(intptr_t)] ;
    61 } ;
    63 // Endian-ness ... index of least-significant byte in SplitWord.Bytes[]
    64 #ifdef AMD64        // little
    65  #define _LSBINDEX 0
    66 #else
    67 #if IA32            // little
    68  #define _LSBINDEX 0
    69 #else
    70 #ifdef SPARC        // big
    71  #define _LSBINDEX (sizeof(intptr_t)-1)
    72 #else
    73  #error "unknown architecture"
    74 #endif
    75 #endif
    76 #endif
    78 class ParkEvent ;
    80 // See orderAccess.hpp.  We assume throughout the VM that mutex lock and
    81 // try_lock do fence-lock-acquire, and that unlock does a release-unlock,
    82 // *in that order*.  If their implementations change such that these
    83 // assumptions are violated, a whole lot of code will break.
    85 // The default length of monitor name is chosen to be 64 to avoid false sharing.
    86 static const int MONITOR_NAME_LEN = 64;
    88 class Monitor : public CHeapObj {
    90  public:
    91   // A special lock: Is a lock where you are guaranteed not to block while you are
    92   // holding it, i.e., no vm operation can happen, taking other locks, etc.
    93   // NOTE: It is critical that the rank 'special' be the lowest (earliest)
    94   // (except for "event"?) for the deadlock dection to work correctly.
    95   // The rank native is only for use in Mutex's created by JVM_RawMonitorCreate,
    96   // which being external to the VM are not subject to deadlock detection.
    97   // The rank safepoint is used only for synchronization in reaching a
    98   // safepoint and leaving a safepoint.  It is only used for the Safepoint_lock
    99   // currently.  While at a safepoint no mutexes of rank safepoint are held
   100   // by any thread.
   101   // The rank named "leaf" is probably historical (and should
   102   // be changed) -- mutexes of this rank aren't really leaf mutexes
   103   // at all.
   104   enum lock_types {
   105        event,
   106        special,
   107        suspend_resume,
   108        leaf        = suspend_resume +   2,
   109        safepoint   = leaf           +  10,
   110        barrier     = safepoint      +   1,
   111        nonleaf     = barrier        +   1,
   112        max_nonleaf = nonleaf        + 900,
   113        native      = max_nonleaf    +   1
   114   };
   116   // The WaitSet and EntryList linked lists are composed of ParkEvents.
   117   // I use ParkEvent instead of threads as ParkEvents are immortal and
   118   // type-stable, meaning we can safely unpark() a possibly stale
   119   // list element in the unlock()-path.
   121  protected:                              // Monitor-Mutex metadata
   122   SplitWord _LockWord ;                  // Contention queue (cxq) colocated with Lock-byte
   123   enum LockWordBits { _LBIT=1 } ;
   124   Thread * volatile _owner;              // The owner of the lock
   125                                          // Consider sequestering _owner on its own $line
   126                                          // to aid future synchronization mechanisms.
   127   ParkEvent * volatile _EntryList ;      // List of threads waiting for entry
   128   ParkEvent * volatile _OnDeck ;         // heir-presumptive
   129   volatile intptr_t _WaitLock [1] ;      // Protects _WaitSet
   130   ParkEvent * volatile  _WaitSet ;       // LL of ParkEvents
   131   volatile bool     _snuck;              // Used for sneaky locking (evil).
   132   int NotifyCount ;                      // diagnostic assist
   133   char _name[MONITOR_NAME_LEN];          // Name of mutex
   135   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
   136 #ifndef PRODUCT
   137   bool      _allow_vm_block;
   138   debug_only(int _rank;)                 // rank (to avoid/detect potential deadlocks)
   139   debug_only(Monitor * _next;)           // Used by a Thread to link up owned locks
   140   debug_only(Thread* _last_owner;)       // the last thread to own the lock
   141   debug_only(static bool contains(Monitor * locks, Monitor * lock);)
   142   debug_only(static Monitor * get_least_ranked_lock(Monitor * locks);)
   143   debug_only(Monitor * get_least_ranked_lock_besides_this(Monitor * locks);)
   144 #endif
   146   void set_owner_implementation(Thread* owner)                        PRODUCT_RETURN;
   147   void check_prelock_state     (Thread* thread)                       PRODUCT_RETURN;
   148   void check_block_state       (Thread* thread)                       PRODUCT_RETURN;
   150   // platform-dependent support code can go here (in os_<os_family>.cpp)
   151  public:
   152   enum {
   153     _no_safepoint_check_flag    = true,
   154     _allow_vm_block_flag        = true,
   155     _as_suspend_equivalent_flag = true
   156   };
   158   enum WaitResults {
   159     CONDVAR_EVENT,         // Wait returned because of condition variable notification
   160     INTERRUPT_EVENT,       // Wait returned because waiting thread was interrupted
   161     NUMBER_WAIT_RESULTS
   162   };
   164  private:
   165    int  TrySpin (Thread * Self) ;
   166    int  TryLock () ;
   167    int  TryFast () ;
   168    int  AcquireOrPush (ParkEvent * ev) ;
   169    void IUnlock (bool RelaxAssert) ;
   170    void ILock (Thread * Self) ;
   171    int  IWait (Thread * Self, jlong timo);
   172    int  ILocked () ;
   174  protected:
   175    static void ClearMonitor (Monitor * m, const char* name = NULL) ;
   176    Monitor() ;
   178  public:
   179   Monitor(int rank, const char *name, bool allow_vm_block=false);
   180   ~Monitor();
   182   // Wait until monitor is notified (or times out).
   183   // Defaults are to make safepoint checks, wait time is forever (i.e.,
   184   // zero), and not a suspend-equivalent condition. Returns true if wait
   185   // times out; otherwise returns false.
   186   bool wait(bool no_safepoint_check = !_no_safepoint_check_flag,
   187             long timeout = 0,
   188             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
   189   bool notify();
   190   bool notify_all();
   193   void lock(); // prints out warning if VM thread blocks
   194   void lock(Thread *thread); // overloaded with current thread
   195   void unlock();
   196   bool is_locked() const                     { return _owner != NULL; }
   198   bool try_lock(); // Like lock(), but unblocking. It returns false instead
   200   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
   201   // that is guaranteed not to block while running inside the VM.
   202   void lock_without_safepoint_check();
   203   void lock_without_safepoint_check (Thread * Self) ;
   205   // Current owner - not not MT-safe. Can only be used to guarantee that
   206   // the current running thread owns the lock
   207   Thread* owner() const         { return _owner; }
   208   bool owned_by_self() const;
   210   // Support for JVM_RawMonitorEnter & JVM_RawMonitorExit. These can be called by
   211   // non-Java thread. (We should really have a RawMonitor abstraction)
   212   void jvm_raw_lock();
   213   void jvm_raw_unlock();
   214   const char *name() const                  { return _name; }
   216   void print_on_error(outputStream* st) const;
   218   #ifndef PRODUCT
   219     void print_on(outputStream* st) const;
   220     void print() const                      { print_on(tty); }
   221     debug_only(int    rank() const          { return _rank; })
   222     bool   allow_vm_block()                 { return _allow_vm_block; }
   224     debug_only(Monitor *next()  const         { return _next; })
   225     debug_only(void   set_next(Monitor *next) { _next = next; })
   226   #endif
   228   void set_owner(Thread* owner) {
   229   #ifndef PRODUCT
   230     set_owner_implementation(owner);
   231     debug_only(void verify_Monitor(Thread* thr));
   232   #else
   233     _owner = owner;
   234   #endif
   235   }
   237 };
   239 // Normally we'd expect Monitor to extend Mutex in the sense that a monitor
   240 // constructed from pthreads primitives might extend a mutex by adding
   241 // a condvar and some extra metadata.  In fact this was the case until J2SE7.
   242 //
   243 // Currently, however, the base object is a monitor.  Monitor contains all the
   244 // logic for wait(), notify(), etc.   Mutex extends monitor and restricts the
   245 // visiblity of wait(), notify(), and notify_all().
   246 //
   247 // Another viable alternative would have been to have Monitor extend Mutex and
   248 // implement all the normal mutex and wait()-notify() logic in Mutex base class.
   249 // The wait()-notify() facility would be exposed via special protected member functions
   250 // (e.g., _Wait() and _Notify()) in Mutex.  Monitor would extend Mutex and expose wait()
   251 // as a call to _Wait().  That is, the public wait() would be a wrapper for the protected
   252 // _Wait().
   253 //
   254 // An even better alternative is to simply eliminate Mutex:: and use Monitor:: instead.
   255 // After all, monitors are sufficient for Java-level synchronization.   At one point in time
   256 // there may have been some benefit to having distinct mutexes and monitors, but that time
   257 // has past.
   258 //
   259 // The Mutex/Monitor design parallels that of Java-monitors, being based on
   260 // thread-specific park-unpark platform-specific primitives.
   263 class Mutex : public Monitor {      // degenerate Monitor
   264  public:
   265    Mutex (int rank, const char *name, bool allow_vm_block=false);
   266    ~Mutex () ;
   267  private:
   268    bool notify ()    { ShouldNotReachHere(); return false; }
   269    bool notify_all() { ShouldNotReachHere(); return false; }
   270    bool wait (bool no_safepoint_check, long timeout, bool as_suspend_equivalent) {
   271      ShouldNotReachHere() ;
   272      return false ;
   273    }
   274 };
   276 /*
   277  * Per-thread blocking support for JSR166. See the Java-level
   278  * Documentation for rationale. Basically, park acts like wait, unpark
   279  * like notify.
   280  *
   281  * 6271289 --
   282  * To avoid errors where an os thread expires but the JavaThread still
   283  * exists, Parkers are immortal (type-stable) and are recycled across
   284  * new threads.  This parallels the ParkEvent implementation.
   285  * Because park-unpark allow spurious wakeups it is harmless if an
   286  * unpark call unparks a new thread using the old Parker reference.
   287  *
   288  * In the future we'll want to think about eliminating Parker and using
   289  * ParkEvent instead.  There's considerable duplication between the two
   290  * services.
   291  *
   292  */
   294 class Parker : public os::PlatformParker {
   295 private:
   296   volatile int _counter ;
   297   Parker * FreeNext ;
   298   JavaThread * AssociatedWith ; // Current association
   300 public:
   301   Parker() : PlatformParker() {
   302     _counter       = 0 ;
   303     FreeNext       = NULL ;
   304     AssociatedWith = NULL ;
   305   }
   306 protected:
   307   ~Parker() { ShouldNotReachHere(); }
   308 public:
   309   // For simplicity of interface with Java, all forms of park (indefinite,
   310   // relative, and absolute) are multiplexed into one call.
   311   void park(bool isAbsolute, jlong time);
   312   void unpark();
   314   // Lifecycle operators
   315   static Parker * Allocate (JavaThread * t) ;
   316   static void Release (Parker * e) ;
   317 private:
   318   static Parker * volatile FreeList ;
   319   static volatile int ListLock ;
   320 };

mercurial