org.jikesrvm.scheduler
Class RVMThread

java.lang.Object
  extended by org.mmtk.plan.MutatorContext
      extended by org.mmtk.plan.SimpleMutator
          extended by org.mmtk.plan.StopTheWorldMutator
              extended by org.mmtk.plan.generational.GenMutator
                  extended by org.mmtk.plan.generational.immix.GenImmixMutator
                      extended by org.jikesrvm.mm.mminterface.Selected.Mutator
                          extended by org.jikesrvm.mm.mminterface.ThreadContext
                              extended by org.jikesrvm.scheduler.RVMThread
All Implemented Interfaces:
HeapLayoutConstants, ThinLockConstants, TIBLayoutConstants, SizeConstants, Constants

public final class RVMThread
extends ThreadContext
implements Constants

A generic java thread's execution context.

Threads use a state machine to indicate to other threads, as well as VM services, how this thread should be treated in the case of an asynchronous request, for example in the case of GC. The state machine uses the following states:

The following state transitions are legal: Observe that the transitions from BLOCKED_IN_NATIVE and BLOCKED_IN_JNI to IN_JAVA constitute a safe point. Code running in BLOCKED_IN_NATIVE or BLOCKED_IN_JNI is "GC safe" but is not quite at a safe point; safe points are special in that they allow the thread to perform async activities (such as mutator flushes or isyncs), while GC safe code will not necessarily perform either.

See Also:
CollectorThread, FinalizerThread, Organizer

Nested Class Summary
(package private) static class RVMThread.AllButGCHardHandshakeVisitor
           
static class RVMThread.BlockAdapter
          A block adapter specifies the reason for blocking or unblocking a thread.
static class RVMThread.GCBlockAdapter
           
static class RVMThread.HandshakeBlockAdapter
           
static class RVMThread.HardHandshakeVisitor
           
static class RVMThread.SoftHandshakeVisitor
           
static class RVMThread.SuspendBlockAdapter
           
protected static class RVMThread.Waiting
          An enumeration that describes the different manners in which a thread might be voluntarily waiting.
 
Field Summary
private static int[] aboutToTerminate
          Thread slots of threads that are about to terminate.
private static int aboutToTerminateN
          Number of threads that are about to terminate.
static NoYieldpointsMonitor acctLock
          Lock (mutex) used for creating and destroying threads as well as thread accounting.
 boolean activeMutatorContext
          Is this a "registered mutator?"
static RVMThread.AllButGCHardHandshakeVisitor allButGC
           
static boolean ALWAYS_LOCK_ON_STATE_TRANSITION
           
(package private)  int arrayIndexTrapParam
          "hidden parameter" from ArrayIndexOutOfBounds trap to C trap handler
 boolean asyncDebugRequestedForThisThread
           
(package private)  Throwable asyncThrowable
          Exception to throw in this thread at the earliest possible point.
(package private)  boolean atYieldpoint
          Are we at a yieldpoint right now?
static int availableProcessors
          The number of processors to use.
(package private)  SpinLock awaitingSpinLock
          Used to handle contention for spin locks
static int BACKEDGE
           
 int barriersEntered
           
 int barriersExited
           
(package private) static RVMThread.BlockAdapter[] blockAdapters
           
static int BLOCKED_IN_JNI
          like BLOCKED_IN_NATIVE, but indicates that the thread is in JNI rather than VM native code.
static int BLOCKED_IN_NATIVE
          thread is in native code, and is to block before returning to Java code.
static RVMThread bootThread
          The boot thread, can't be final so as to allow initialization during boot image writing.
 ArchitectureSpecific.CodeArray bridgeInstructions
          Before call new instructions, we need a bridge to recover register states from the stack frame.
 Lock cachedFreeLock
          A cached free lock.
 boolean codePatchSyncRequested
          flag indicating this processor needs to execute a memory synchronization sequence Used for code patching on SMP PowerPCs.
private  int collectionAttempt
          Used by GC to determine collection success
private static Monitor[] communicationLockBySlot
           
(package private)  RVMThread contenderLink
           
 ArchitectureSpecific.Registers contextRegisters
          Place to save register state when this thread is not actually running.
 ArchitectureSpecific.Registers contextRegistersSave
          Place to save register state when this thread is not actually running.
private  ArchitectureSpecific.Registers contextRegistersSaveShadow
           
private  ArchitectureSpecific.Registers contextRegistersShadow
           
 int countdownCBSCall
          Number of call yieldpoints between CBS samples
 int countdownCBSMethod
          Number of counter ticks between CBS samples
protected  boolean daemon
          The virtual machine terminates when the last non-daemon (user) thread terminates.
static boolean DEBUG_STACK_TRAMPOLINE
          debugging flag for return barrier trampoline
static NoYieldpointsMonitor debugLock
          Lock (mutex) used for servicing debug requests.
static boolean debugRequested
          Flag set by external signal to request debugger activation at next thread switch.
static RVMThread[] debugThreads
          Preallocated array for use in debug requested.
private  int disableGCDepth
          Counts the depth of outstanding calls to VM.disableGC().
private  boolean disallowAllocationsByThisThread
          Assertion checking while manipulating raw addresses -- see VM.disableGC()/VM.enableGC().
static Latch doProfileReport
          The latch for reporting profile data.
static Monitor dumpLock
          Lock used for dumping stack and such.
protected static boolean dumpStackOnBlock
           
static int EPILOGUE
           
private  ArchitectureSpecific.Registers exceptionRegisters
          Place to save register state during hardware(C signal trap handler) or software (RuntimeEntrypoints.athrow) trap handling.
private  ArchitectureSpecific.Registers exceptionRegistersShadow
           
private  int execStatus
          Thread state.
(package private) static int[] execStatusTransitionHistogram
           
protected static boolean exitInProgress
          In dump stack and dying
 Feedlet feedlet
          The Feedlet instance for this thread to use to make addEvent calls.
 int firstCBSCallSample
          round robin starting point for CBS samples
 int firstCBSMethodSample
          round robin starting point for CBS samples
 boolean flushRequested
          Is there a flush request for this thread?
 Offset fooFPOffset
          Foo frame pointer offset
(package private)  Address framePointer
          FP for current frame, saved in the prologue of every method
private static int freeSlotN
          Number of free thread slots.
private static int[] freeSlots
          Free thread slots
static RVMThread.GCBlockAdapter gcBlockAdapter
           
static RVMThread.HandshakeBlockAdapter handshakeBlockAdapter
           
static Monitor handshakeLock
          Lock that prevents multiple (soft or hard) handshakes from proceeding concurrently.
static RVMThread[] handshakeThreads
          Preallocated array for use in handshakes.
(package private)  boolean hasInterrupt
          Has the thread been interrupted?
(package private)  int hiddenSignatureId
          "hidden parameter" for interface invocation thru the IMT
private  Address hijackedReturnAddress
          Return address of stack frame hijacked by return barrier
private  Address hijackedReturnCalleeFp
          Callee frame pointer for stack frame hijacked by return barrier
private  Address hijackedReturnCallerFp
          Caller frame pointer for stack frame hijacked by return barrier
static int IN_JAVA
          Thread is executing "normal" Java bytecode
static int IN_JAVA_TO_BLOCK
          thread is in Java code but is expected to block. the transition from IN_JAVA to IN_jAVA_TO_BLOCK happens as a result of an asynchronous call by the GC or any other internal VM code that requires this thread to perform an asynchronous activity (another example is the request to do an isync on PPC).
static int IN_JNI
          Same as IN_NATIVE, except that we're executing JNI code and thus have a JNI stack frame and JNI environment, and thus the GC can load registers from there rather than using contextRegisters.
static int IN_NATIVE
          A state used by the scheduler to mark that a thread is in privileged code that does not need to synchronize with the collector.
protected  int inDumpStack
          Number of times dump stack has been called recursively
private  boolean isAboutToTerminate
          Is the thread about to terminate?
(package private)  boolean isBlockedForGC
          Is the thread blocked for thread-to-thread communication?
(package private)  boolean isBlockedForHandshake
          Is the thread blocked for handshake?
(package private)  boolean isBlocking
          Is this thread in the process of blocking?
(package private)  boolean isJoinable
          Is the thread no longer executing user code?
(package private)  boolean isSuspended
          Is the thread suspended?
 boolean isWaitingForOsr
          The flag indicates whether this thread is waiting for on stack replacement before being rescheduled.
private  long jniEnteredBlocked
           
private  JNIEnvironment jniEnv
          Cached JNI environment for this thread
private  JNIEnvironment jniEnvShadow
           
static int LAST_EXEC_STATUS
          Not actually a state but just a marker.
 int lockingId
           
static int LOG_MAX_THREADS
          Maximum number of RVMThread's that we can support.
static int MAX_THREADS
           
private static NoYieldpointsMonitor[] monitorBySlot
          Per-thread monitors.
private  String name
          Name of the thread (can be changed during execution)
static int NATIVE_EPILOGUE
           
static int NATIVE_PROLOGUE
           
private  long nativeEnteredBlocked
           
private static boolean neverKillThreads
          Never kill threads.
static int NEW
          Thread has not yet started.
(package private)  RVMThread next
          Link pointer for queues (specifically ThreadQueue).
static int nextSlot
          When there are no thread slots on the free list, this is the next one to use.
(package private) static int notifyAllOperations
          Number of notifyAll operations
(package private) static int notifyOperations
          Number of notify operations
private static int numActiveDaemons
          Number of active daemon threads.
private static int numActiveThreads
          Number of active threads in the system.
 int numCBSCallSamples
          Number of CBS samples to take in this window
 int numCBSMethodSamples
          Number of CBS samples to take in this window
static int numThreads
          Number of threads in the system (some of which may not be active).
 Object onStackReplacementEvent
          Only used by OSR when VM.BuildForAdaptiveSystem.
 boolean osr_done
          Flag to indicate that the last OSR request is done.
static int OSROPT
           
private static OutOfMemoryError outOfMemoryError
          The OOME to throw
private static NoYieldpointsMonitor outputLock
          Lock used for generating debug output.
private  boolean parkingPermit
          Is a running thread permitted to ignore the next park request
private  boolean physicalAllocationFailed
          Used by GC to determine collection success
static int PRIMORDIAL_THREAD_INDEX
          Index of thread in which "VM.boot()" runs
private  int priority
          Scheduling priority for this thread.
static int PROLOGUE
           
 Word pthread_id
          Thread handle.
(package private)  ThreadQueue queuedOn
          The queue that the thread is on, or null if the thread is not on a queue (specifically ThreadQueue).
 boolean requesting_osr
          Flag to synchronize with osr organizer, the trigger sets osr requests the organizer clear the requests
private  double scratchStorage
          Scratch area for use for gpr <=> fpr transfers by PPC baseline compiler.
(package private)  boolean shouldBlockForGC
          Should the thread block for a thread-to-thread communication?
(package private)  boolean shouldBlockForHandshake
          Should the thread block for handshake?
(package private)  boolean shouldSuspend
          Should the thread suspend?
(package private)  int shouldSuspendToken
          An integer token identifying the last suspend request
private static boolean SHOW_FP_IN_STACK_DUMP
          Toggle display of frame pointer address in stack dump
(package private) static int[] sloppyExecStatusHistogram
           
static Monitor softHandshakeDataLock
          Lock that protects soft handshake fields.
static int softHandshakeLeft
          How many threads have not yet reached the soft handshake?
 boolean softHandshakeRequested
          Is a soft handshake requested?
private  byte[] stack
          Execution stack for this thread.
 Address stackLimit
          The Address of the guard area for stack.
static ArchitectureSpecific.CodeArray stackTrampolineBridgeInstructions
          pointer to bridge code for return barrier trampoline
private static boolean STATS
          Generate statistics?
(package private) static int[] statusAtSTWHistogram
           
static RVMThread.SuspendBlockAdapter suspendBlockAdapter
           
private static boolean systemShuttingDown
          Is the system in the process of shutting down (has System.exit been called)
private  SystemThread systemThread
          Non-null indicates this is a system thread, that is one used by the system and as such doesn't have a Runnable...
 int takeYieldpoint
          Should the next executed yieldpoint be taken?
static int TERMINATED
          Thread has died.
private  Thread thread
          java.lang.Thread wrapper for this Thread.
 int thread_cbs_counter
          For builds using counter-based sampling.
static RVMThread[] threadBySlot
          thread array - all threads are stored in this array according to their threadSlot.
private  int threadIdx
          Current index of this thread in the threads array.
static boolean threadingInitialized
          Is the threading system initialized?
static RVMThread[] threads
          Packed and unordered array or active threads.
 int threadSlot
          Index of this thread in threadBySlot[].
(package private) static int timedWaitOperations
          Number of timed wait operations
static long timerTicks
          Number of timer ticks we've seen
 int timeSliceExpired
          How many times has the "timeslice" expired?
(package private) static long totalResumeTime
           
(package private) static long totalSuspendTime
           
protected static boolean trace
          Trace execution
protected static boolean traceAboutToTerminate
           
protected static boolean traceAcct
          Trace thread start/stop
private static boolean traceAdjustments
          Trace adjustments to stack size
protected static boolean traceBind
           
protected static boolean traceBlock
          Trace thread blockage
protected static boolean traceDetails
          Extra debug from traces
protected static boolean traceReallyBlock
          Trace when a thread is really blocked
private static boolean traceTermination
          Trace thread termination
private  ArchitectureSpecific.Registers trampolineRegisters
          Registers used by return barrier trampoline
 Offset tsFPOffset
          Thread switch frame pointer offset
private  int uncaughtExceptionCount
          Count of recursive uncaught exceptions, we need to bail out at some point
protected  int waitCount
          Lock recursion count for this thread's monitor.
protected  RVMThread.Waiting waiting
          Accounting of whether or not a thread is waiting (in the Java thread state sense), and if so, how it's waiting.
protected  Object waitObject
          Place to save/restore this thread's monitor state during Object.wait() and Object.notify().
(package private) static int waitOperations
          Number of wait operations
private static boolean worldStopped
           
 boolean yieldForCBSCall
          Is CBS enabled for 'call' yieldpoints?
 boolean yieldForCBSMethod
          Is CBS enabled for 'method' yieldpoints?
(package private)  boolean yieldpointRequestPending
          Is a takeYieldpoint request pending on this thread?
private  int yieldpointsEnabledCount
          Should this thread yield at yieldpoints?
private  long yieldpointsTaken
           
private  long yieldpointsTakenFully
           
 boolean yieldToOSRRequested
          Is the next taken yieldpoint in response to a request to perform OSR?
 
Fields inherited from class org.jikesrvm.mm.mminterface.ThreadContext
collectorContext
 
Fields inherited from class org.mmtk.plan.generational.GenMutator
arrayRemset, nursery, remset
 
Fields inherited from class org.mmtk.plan.MutatorContext
immortal, lgcode, log, los, nonmove, smcode
 
Fields inherited from interface org.jikesrvm.Constants
NOT_REACHED, REFLECTION_FPRS_BITS, REFLECTION_FPRS_MASK, REFLECTION_GPRS_BITS, REFLECTION_GPRS_MASK
 
Fields inherited from interface org.jikesrvm.objectmodel.ThinLockConstants
TL_DEDICATED_U16_OFFSET, TL_DEDICATED_U16_SHIFT, TL_LOCK_COUNT_MASK, TL_LOCK_COUNT_SHIFT, TL_LOCK_COUNT_UNIT, TL_LOCK_ID_MASK, TL_LOCK_ID_SHIFT, TL_NUM_BITS_RC, TL_NUM_BITS_STAT, TL_NUM_BITS_TID, TL_STAT_BIASABLE, TL_STAT_FAT, TL_STAT_MASK, TL_STAT_SHIFT, TL_STAT_THIN, TL_THREAD_ID_MASK, TL_THREAD_ID_SHIFT, TL_UNLOCK_MASK
 
Fields inherited from interface org.jikesrvm.SizeConstants
BITS_IN_ADDRESS, BITS_IN_BOOLEAN, BITS_IN_BYTE, BITS_IN_CHAR, BITS_IN_DOUBLE, BITS_IN_EXTENT, BITS_IN_FLOAT, BITS_IN_INT, BITS_IN_LONG, BITS_IN_OFFSET, BITS_IN_PAGE, BITS_IN_SHORT, BITS_IN_WORD, BYTES_IN_ADDRESS, BYTES_IN_BOOLEAN, BYTES_IN_BYTE, BYTES_IN_CHAR, BYTES_IN_DOUBLE, BYTES_IN_EXTENT, BYTES_IN_FLOAT, BYTES_IN_INT, BYTES_IN_LONG, BYTES_IN_OFFSET, BYTES_IN_PAGE, BYTES_IN_SHORT, BYTES_IN_WORD, LOG_BITS_IN_ADDRESS, LOG_BITS_IN_BOOLEAN, LOG_BITS_IN_BYTE, LOG_BITS_IN_CHAR, LOG_BITS_IN_DOUBLE, LOG_BITS_IN_EXTENT, LOG_BITS_IN_FLOAT, LOG_BITS_IN_INT, LOG_BITS_IN_LONG, LOG_BITS_IN_OFFSET, LOG_BITS_IN_PAGE, LOG_BITS_IN_SHORT, LOG_BITS_IN_WORD, LOG_BYTES_IN_ADDRESS, LOG_BYTES_IN_BOOLEAN, LOG_BYTES_IN_BYTE, LOG_BYTES_IN_CHAR, LOG_BYTES_IN_DOUBLE, LOG_BYTES_IN_EXTENT, LOG_BYTES_IN_FLOAT, LOG_BYTES_IN_INT, LOG_BYTES_IN_LONG, LOG_BYTES_IN_OFFSET, LOG_BYTES_IN_PAGE, LOG_BYTES_IN_SHORT, LOG_BYTES_IN_WORD
 
Fields inherited from interface org.jikesrvm.objectmodel.TIBLayoutConstants
IMT_METHOD_SLOTS, NEEDS_DYNAMIC_LINK, TIB_ARRAY_ELEMENT_TIB_INDEX, TIB_DOES_IMPLEMENT_INDEX, TIB_FIRST_SPECIALIZED_METHOD_INDEX, TIB_FIRST_VIRTUAL_METHOD_INDEX, TIB_INTERFACE_DISPATCH_TABLE_INDEX, TIB_SUPERCLASS_IDS_INDEX, TIB_TYPE_INDEX
 
Fields inherited from interface org.jikesrvm.HeapLayoutConstants
BAD_MAP_COMPRESSION, BOOT_IMAGE_CODE_END, BOOT_IMAGE_CODE_SIZE, BOOT_IMAGE_CODE_START, BOOT_IMAGE_DATA_END, BOOT_IMAGE_DATA_SIZE, BOOT_IMAGE_DATA_START, BOOT_IMAGE_END, BOOT_IMAGE_RMAP_END, BOOT_IMAGE_RMAP_START, MAX_BOOT_IMAGE_RMAP_SIZE, MAXIMUM_MAPPABLE
 
Fields inherited from interface org.mmtk.utility.Constants
ALIGNMENT_VALUE, ARRAY_ELEMENT, BITS_IN_ADDRESS, BITS_IN_BYTE, BITS_IN_CHAR, BITS_IN_INT, BITS_IN_PAGE, BITS_IN_SHORT, BITS_IN_WORD, BYTES_IN_ADDRESS, BYTES_IN_BYTE, BYTES_IN_CHAR, BYTES_IN_INT, BYTES_IN_KBYTE, BYTES_IN_MBYTE, BYTES_IN_PAGE, BYTES_IN_SHORT, BYTES_IN_WORD, CARD_MASK, CARD_META_PAGES_PER_REGION, INSTANCE_FIELD, LOG_BITS_IN_ADDRESS, LOG_BITS_IN_BYTE, LOG_BITS_IN_CHAR, LOG_BITS_IN_INT, LOG_BITS_IN_PAGE, LOG_BITS_IN_SHORT, LOG_BITS_IN_WORD, LOG_BYTES_IN_ADDRESS, LOG_BYTES_IN_ADDRESS_SPACE, LOG_BYTES_IN_BYTE, LOG_BYTES_IN_CHAR, LOG_BYTES_IN_INT, LOG_BYTES_IN_KBYTE, LOG_BYTES_IN_MBYTE, LOG_BYTES_IN_PAGE, LOG_BYTES_IN_SHORT, LOG_BYTES_IN_WORD, LOG_CARD_BYTES, LOG_CARD_GRAIN, LOG_CARD_META_BYTES, LOG_CARD_META_PAGES, LOG_CARD_META_SIZE, LOG_CARD_UNITS, LOG_MIN_ALIGNMENT, MAX_ALIGNMENT, MAX_BYTES_PADDING, MAX_INT, MIN_ALIGNMENT, MIN_INT, SUPPORT_CARD_SCANNING
 
Constructor Summary
RVMThread(byte[] stack, Thread thread, String name, boolean daemon, SystemThread systemThread, int priority)
          Create a new RVM Thread
RVMThread(SystemThread systemThread, byte[] stack, String name)
          Create a thread with the given stack and name.
RVMThread(SystemThread systemThread, String name)
          Create a thread with default stack and with the given name.
RVMThread(Thread thread, long stacksize, String name, boolean daemon, int priority)
          Create a thread with ... called by java.lang.VMThread.create.
 
Method Summary
private static void _trace(String who, String what, int howmany, boolean hex)
           
private  void acknowledgeBlockRequests()
          Check if the thread has block requests (for example, for suspension and GC).
private  void addAboutToTerminate()
          Add this thread to the termination watchlist.
private static void adjustRegisters(ArchitectureSpecific.Registers registers, Offset delta)
          A thread's stack has been moved or resized.
private static void adjustStack(byte[] stack, Address fp, Offset delta)
          A thread's stack has been moved or resized.
 void assertAcceptableStates(int expected)
           
 void assertAcceptableStates(int expected1, int expected2)
           
 void assertUnacceptableStates(int unexpected)
           
 void assertUnacceptableStates(int unexpected1, int unexpected2)
           
(package private)  void assignThreadSlot()
          Find a thread slot not in use by any other live thread and bind the given thread to it.
 int asyncBlock(RVMThread.BlockAdapter ba)
           
private  boolean attemptFastExecStatusTransition(int oldState, int newState)
           
static boolean attemptLeaveNativeNoBlock()
          Attempt to transition from IN_JNI or IN_NATIVE to IN_JAVA, fail if execStatus is anything but IN_JNI or IN_NATIVE.
 void beginPairHandshake()
           
 void beginPairWith(RVMThread other)
           
 void beginPairWithCurrent()
           
(package private) static void bind(int cpuId)
           
(package private) static void bindIfRequested()
           
 int block(RVMThread.BlockAdapter ba)
           
(package private)  int block(RVMThread.BlockAdapter ba, boolean asynchronous)
          Attempt to block the thread, and return the state it is in after the attempt.
static void blockAllMutatorsForGC()
          Stop all mutator threads.
 boolean blockedFor(RVMThread.BlockAdapter ba)
           
static void boot()
          Boot the threading subsystem.
private  void callSystemExit(int exitStatus)
          Call System.exit() with the correct security status.
(package private)  void checkBlock()
          Check if the thread is supposed to block, and if so, block it.
private  void checkBlockNoSaveContext()
          A variant of checkBlock() that does not save the thread state.
static void checkDebugRequest()
           
 void clearDisallowAllocationsByThisThread()
          Allow allocations by this thread
 void clearInterrupted()
          Clear the interrupted status of this thread
 void clearPhysicalAllocationFailed()
          Clear the physical allocation failed flag.
 Monitor communicationLock()
           
 Monitor communicationLockForSlot(int slot)
           
private static Offset copyStack(byte[] newStack)
          Initialize a new stack with the live portion of the stack we're currently running on.
 int countStackFrames()
          Count the stack frames of this thread
 void deInstallStackTrampoline()
          de-install the stack trampoline (disabling return barriers).
 void disableYieldpoints()
          Disable yieldpoints on this thread.
 void dump()
          Dump this thread's identifying information, for debugging, via VM.sysWrite(String).
 int dump(char[] dest)
          Dump this thread's info, for debugging.
 int dump(char[] dest, int offset)
          Dump this thread's info, for debugging.
 void dump(int verbosity)
          Dump this thread's identifying information, for debugging, via VM.sysWrite(String).
(package private) static void dump1DHisto(String name, int[] histo)
           
static void dumpAcct()
           
static void dumpAll(int verbosity)
          Dump information for all threads, via VM.sysWrite(String).
private static void dumpFrame(Address fp)
          Dump the specified frame in a format useful for debugging the stack trampoline
static void dumpStack()
          Dump stack of calling thread, starting at callers frame
static void dumpStack(Address fp)
          Dump state of a (stopped) thread's stack.
static void dumpStack(Address ip, Address fp)
          Dump state of a (stopped) thread's stack.
static void dumpStackAndDie(Address fp)
          Dump state of a (stopped) thread's stack and exit the virtual machine.
(package private) static void dumpStats()
          Dump statistics gather on operations
private static void dumpThread(RVMThread t)
           
private static void dumpThreadArray(RVMThread[] array, int bound)
           
private static void dumpThreadArray(String name, RVMThread[] array, int bound)
           
private static void dumpThreadSlotArray(int[] array, int bound)
           
private static void dumpThreadSlotArray(String name, int[] array, int bound)
           
static void dumpVirtualMachine()
          Dump state of virtual machine.
 void dumpWithPadding(int leftJustify)
          Dump this thread's identifying information, for debugging, via VM.sysWrite(String).
 void enableYieldpoints()
          Enable yieldpoints on this thread.
 void endPairHandshake()
           
 void endPairWith(RVMThread other)
           
 void endPairWithCurrent()
           
private  void enterJNIBlocked()
           
static void enterJNIBlockedFromCallIntoNative()
           
static void enterJNIBlockedFromJNIFunctionCall()
           
static void enterJNIFromCallIntoNative()
           
static void enterJNIFromJNIFunctionCall()
           
static void enterNative()
          Indicate that we'd like the current thread to be executing privileged code that does not require synchronization with the GC.
private  void enterNativeBlocked()
           
private  void enterNativeBlockedImpl(boolean jni)
          Internal method for transitioning a thread from IN_JAVA or IN_JAVA_TO_BLOCK to either BLOCKED_IN_NATIVE or BLOCKED_IN_JNI, depending on the value of the jni parameter.
 void extDump()
           
 void failIfYieldpointsDisabled()
          Fail if yieldpoints are disabled on this thread
(package private)  void finishThreadTermination()
          Uninterruptible final portion of thread termination.
 void fixupMovedStack(Offset delta)
          This (suspended) thread's stack has been moved.
static boolean gcEnabled()
          Is it safe to start forcing garbage collects for stress testing?
 int getCollectionAttempt()
          Set the initial attempt.
 CollectorThread getCollectorThread()
          Get the collector thread this RVMTHread is running
 ArchitectureSpecific.Registers getContextRegisters()
           
static Feedlet getCurrentFeedlet()
           
static RVMThread getCurrentThread()
           
static int getCurrentThreadSlot()
           
 int getDisableGCDepth()
          Get the disable GC depth
 boolean getDisallowAllocationsByThisThread()
          Are allocations allowed by this thread?
 ArchitectureSpecific.Registers getExceptionRegisters()
           
 int getExecStatus()
           
static Address getHijackedReturnAddress(Address hijackedFp)
          Given a frame that has been hijacked by the stack trampoline, return the real (hijacked) return address.
 Address getHijackedReturnCalleeFp()
           
 boolean getIsAboutToTerminate()
           
 Thread getJavaLangThread()
          Get the current java.lang.Thread.
 JNIEnvironment getJNIEnv()
          Get current thread's JNI environment.
 int getLockingId()
          Get this thread's id for use in lock ownership tests.
 String getName()
          Gets the name of the thread
 Address getNextUnencounteredFrame()
           
static int getNumActiveDaemons()
          Number of active daemon threads.
static int getNumActiveThreads()
          Number of active threads in the system.
static OutOfMemoryError getOutOfMemoryError()
          Returns the outstanding OutOfMemoryError.
 int getPriority()
          Get the priority of the thread
 byte[] getStack()
           
 int getStackLength()
           
private  Address getStackTrampolineBridgeIP()
           
 Thread.State getState()
          Get the state of the thread in a manner compatible with the Java API
 int getThreadSlot()
           
 Address getTrampolineHijackedReturnAddress()
           
private  void handleDebugRequestForThread()
           
(package private)  void handleHandshakeRequest()
          Handle requests that required a soft handshake.
private  void handlePossibleRecursiveException()
          Handle the case of exception handling triggering new exceptions.
 void handleUncaughtException(Throwable exceptionObject)
           
static void hardHandshakeResume()
           
static void hardHandshakeResume(RVMThread.BlockAdapter ba, RVMThread.HardHandshakeVisitor hhv)
           
static void hardHandshakeSuspend()
           
static void hardHandshakeSuspend(RVMThread.BlockAdapter ba, RVMThread.HardHandshakeVisitor hhv)
           
 boolean hasNativeStackFrame()
          Indicate whether the stack of this Thread contains any C frame (used in RuntimeEntrypoints.deliverHardwareException for stack resize)
 boolean holdsLock(Object obj)
          Does the currently running Thread hold the lock on an obj?
 boolean ignoreHandshakesAndGC()
          Should this thread run concurrently with STW GC and ignore handshakes?
static void init()
          Initialize the threading subsystem for the boot image.
 void initializeJNIEnv()
          Initialize JNI environment for system threads.
 void installStackTrampolineBridge(Address targetFp)
          Install the stack trampoline bridge at a given frame, hijacking that frame, saving the hijacked return address and callee fp in thread-local state to allow execution of the hijacked frame later.
 void interrupt()
          Interrupt this thread
private static boolean isAddressValidFramePointer(Address address)
          Return true if the supplied address could be a valid frame pointer.
 boolean isAlive()
          Is the thread started and not terminated
 boolean isBlocked()
          Checks if the thread system has acknowledged that the thread is supposed to be blocked.
 boolean isBootThread()
           
 boolean isDaemonThread()
          Returns the value of daemon.
 boolean isInJava()
          Checks if the thread is executing Java code.
 boolean isInterrupted()
          Was this thread interrupted?
private  boolean isMainThread()
           
 boolean isOnQueue()
           
 boolean isSystemThread()
          Is this a system thread?
static boolean isTrampolineIP(Address ip)
          Determine whether a given method is the stack trampoline
 void join(long ms, int ns)
          Wait for the thread to die or for the timeout to occur
private  void leaveJNIBlocked()
           
static void leaveJNIBlockedFromCallIntoNative()
          Called when JNI code tried to transition from IN_JNI to IN_JAVA but failed
(package private) static void leaveJNIBlockedFromJNIFunctionCall()
           
static void leaveJNIFromCallIntoNative()
           
static void leaveJNIFromJNIFunctionCall()
           
static void leaveNative()
          Leave privileged code.
private  void leaveNativeBlocked()
           
private  void leaveNativeBlockedImpl()
           
 void makeDaemon(boolean on)
          Set the "isDaemon" status of this thread.
 NoYieldpointsMonitor monitor()
          Get the NoYieldpointsCondLock for this thread.
(package private) static NoYieldpointsMonitor monitorForSlot(int slot)
          Get a NoYieldpointsCondLock for a given thread slot.
static void notify(Object o)
          Support for Java Object.notify() synchronization primitive.
static void notifyAll(Object o)
          Support for Java synchronization primitive.
static boolean notRunning(int state)
           
(package private)  void observeExecStatus()
           
static void observeExecStatusAtSTW(int execStatus)
           
(package private) static void observeStateTransition(int oldState, int newState)
           
 void park(boolean isAbsolute, long time)
           
 boolean physicalAllocationFailed()
          Get the physical allocation failed flag.
static void processAboutToTerminate()
          Method called after processing a list of threads, or before starting a new thread.
static void raiseIllegalMonitorStateException(String msg, Object o)
           
(package private)  void releaseThreadSlot()
          Release a thread's slot in the threads array.
 void reportCollectionAttempt()
          Set the initial attempt.
static void reportThreadTransitionCounts()
           
 void resetCollectionAttempts()
          Resets the attempts.
static void resizeCurrentStack(int newSize, ArchitectureSpecific.Registers exceptionRegisters)
          Change the size of the currently executing thread's stack.
 void resume()
          Resume execution of a thread that has been suspended.
static void returnBarrier()
          The return barrier.
 void run()
          Method to be executed when this thread starts running.
 int safeAsyncBlock(RVMThread.BlockAdapter ba)
           
 int safeBlock(RVMThread.BlockAdapter ba)
           
private  int safeBlock(RVMThread.BlockAdapter ba, boolean asynchronous)
           
static boolean safeToForceGCs()
          Is it safe to start forcing garbage collects for stress testing?
static void saveThreadState()
          Save the current thread state.
private  int setBlockedExecStatus()
           
 void setDisableGCDepth(int d)
          Modify the disable GC depth
 void setDisallowAllocationsByThisThread()
          Disallow allocations by this thread
private  void setExecStatus(int newState)
           
 void setName(String name)
          Sets the name of the thread
 void setPhysicalAllocationFailed()
          Set the physical allocation failed flag.
 void setPriority(int priority)
          Set the priority of the thread
 void setupBootJavaThread()
          Called during booting to give the boot thread a java.lang.Thread
static RVMThread setupBootThread()
          Set up the initial thread and processors as part of boot image writing
 boolean shouldBeSampled()
          Should the thread by eligible for sampling by the timer thread?
private static void showMethod(int compiledMethodId, Address fp)
          Show a method where getCompiledMethod returns null
private static void showMethod(RVMMethod method, int lineNumber, Address fp)
          Helper function for dumpStack(Address,Address).
private static void showMethod(String name, Address fp)
          Show a method that we can't show (ie just a text description of the stack frame
private static void showPrologue(Address fp)
           
static void sleep(long ns)
          Suspend execution of current thread for specified number of seconds (or fraction).
static void sleep(long millis, int ns)
          Suspend execution of current thread for specified number of seconds (or fraction).
static int snapshotHandshakeThreads(RVMThread.SoftHandshakeVisitor v)
           
static void softHandshake(RVMThread.SoftHandshakeVisitor v)
          Tell each thread to take a yieldpoint and wait until all of them have done so at least once.
 void softRendezvous()
          Rendezvous with a soft handshake request.
 boolean softRendezvousCheckAndClear()
          Check and clear the need for a soft handshake rendezvous.
 void softRendezvousCommit()
          Commit the soft handshake rendezvous.
 void start()
          Start execution of 'this' by putting it on the appropriate queue of an unspecified virtual processor.
private static void startoff()
          Begin execution of current thread by calling its "run" method.
 void stop(Throwable cause)
           
 void suspend()
          Suspend execution of current thread until it is resumed.
 void terminate()
          Terminate execution of current thread by abandoning all references to it and resuming execution in some other (ready) thread.
private  void terminateUnpreemptible()
          Unpreemptible portion of thread termination.
private static void throwFromUninterruptible(Throwable e)
           
(package private)  void timerTick()
           
 String toString()
          String representation of thread
static void trace(String who, String what)
          Print out message in format "[j] (cez#td) who: what", where: j = java thread id z* = RVMThread.getCurrentThread().yieldpointsEnabledCount (0 means yieldpoints are enabled outside of the call to debug) t* = numActiveThreads d* = numActiveDaemons * parenthetical values, printed only if traceDetails = true) We serialize against a mutex to avoid intermingling debug output from multiple threads.
static void trace(String who, String what, Address addr)
           
static void trace(String who, String what, int howmany)
          Print out message in format "p[j] (cez#td) who: what howmany", where: p = processor id j = java thread id c* = java thread id of the owner of threadCreationMutex (if any) e* = java thread id of the owner of threadExecutionMutex (if any) t* = numActiveThreads d* = numActiveDaemons * parenthetical values, printed only if traceDetails = true) We serialize against a mutex to avoid intermingling debug output from multiple threads.
static void traceback(String message)
          Print interesting scheduler information, starting with a stack traceback.
static void traceback(String message, int number)
           
(package private) static void tracebackWithoutLock()
           
static void traceHex(String who, String what, int howmany)
           
private static void transferExecutionToNewStack(byte[] newStack, ArchitectureSpecific.Registers exceptionRegisters)
           
(package private) static int transitionHistogramIndex(int oldState, int newState)
           
 void unblock(RVMThread.BlockAdapter ba)
           
static void unblockAllMutatorsForGC()
          Unblock all mutators blocked for GC.
 void unpark()
           
static void wait(Object o)
          Support for Java Object.wait() synchronization primitive.
static void wait(Object o, long millis)
          Support for Java Object.wait() synchronization primitive.
static void waitAbsoluteNanos(Object o, long whenNanos)
          Support for RTSJ- and pthread-style absolute wait.
(package private)  void waitImpl(Object o, boolean hasTimeout, long whenWakeupNanos)
           
static boolean worldStopped()
           
static void yieldNoHandshake()
           
static void yieldpoint(int whereFrom, Address yieldpointServiceMethodFP)
          Process a taken yieldpoint.
static void yieldpointFromBackedge()
          Yieldpoint taken on backedge.
static void yieldpointFromEpilogue()
          Yieldpoint taken in epilogue.
static void yieldpointFromPrologue()
          Yieldpoint taken in prologue.
 boolean yieldpointsEnabled()
          Are we allowed to take yieldpoints?
static void yieldWithHandshake()
           
 
Methods inherited from class org.jikesrvm.mm.mminterface.ThreadContext
getCollectorContext, isCollectorThread
 
Methods inherited from class org.jikesrvm.mm.mminterface.Selected.Mutator
get, getThread
 
Methods inherited from class org.mmtk.plan.generational.immix.GenImmixMutator
alloc, collectionPhase, getAllocatorFromSpace, postAlloc
 
Methods inherited from class org.mmtk.plan.generational.GenMutator
assertRemsetsFlushed, flushRememberedSets, objectReferenceBulkCopy, objectReferenceNonHeapWrite, objectReferenceTryCompareAndSwap, objectReferenceWrite
 
Methods inherited from class org.mmtk.plan.MutatorContext
addressBulkCopy, addressRead, addressTryCompareAndSwap, addressWrite, booleanBulkCopy, booleanRead, booleanWrite, byteBulkCopy, byteRead, byteWrite, charBulkCopy, charRead, charWrite, checkAllocator, deinitMutator, doubleBulkCopy, doubleRead, doubleWrite, extentBulkCopy, extentRead, extentWrite, floatBulkCopy, floatRead, floatWrite, flush, getId, getLog, initMutator, intBulkCopy, intRead, intTryCompareAndSwap, intWrite, javaLangReferenceReadBarrier, longBulkCopy, longRead, longTryCompareAndSwap, longWrite, objectReferenceNonHeapRead, objectReferenceRead, offsetBulkCopy, offsetRead, offsetWrite, shortBulkCopy, shortRead, shortWrite, wordBulkCopy, wordRead, wordTryCompareAndSwap, wordWrite
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

traceBlock

protected static final boolean traceBlock
Trace thread blockage

See Also:
Constant Field Values

traceReallyBlock

protected static final boolean traceReallyBlock
Trace when a thread is really blocked

See Also:
Constant Field Values

traceAboutToTerminate

protected static final boolean traceAboutToTerminate
See Also:
Constant Field Values

dumpStackOnBlock

protected static final boolean dumpStackOnBlock
See Also:
Constant Field Values

traceBind

protected static final boolean traceBind
See Also:
Constant Field Values

traceAcct

protected static final boolean traceAcct
Trace thread start/stop

See Also:
Constant Field Values

trace

protected static final boolean trace
Trace execution

See Also:
Constant Field Values

traceTermination

private static final boolean traceTermination
Trace thread termination

See Also:
Constant Field Values

traceAdjustments

private static final boolean traceAdjustments
Trace adjustments to stack size

See Also:
Constant Field Values

neverKillThreads

private static final boolean neverKillThreads
Never kill threads. Useful for testing bugs related to interaction of thread death with for example MMTk. For production, this should never be set to true.

See Also:
Constant Field Values

STATS

private static final boolean STATS
Generate statistics?

See Also:
Constant Field Values

waitOperations

static int waitOperations
Number of wait operations


timedWaitOperations

static int timedWaitOperations
Number of timed wait operations


notifyOperations

static int notifyOperations
Number of notify operations


notifyAllOperations

static int notifyAllOperations
Number of notifyAll operations


ALWAYS_LOCK_ON_STATE_TRANSITION

public static final boolean ALWAYS_LOCK_ON_STATE_TRANSITION
See Also:
Constant Field Values

NEW

public static final int NEW
Thread has not yet started. This state holds right up until just before we call pthread_create().

See Also:
Constant Field Values

IN_JAVA

public static final int IN_JAVA
Thread is executing "normal" Java bytecode

See Also:
Constant Field Values

IN_NATIVE

public static final int IN_NATIVE
A state used by the scheduler to mark that a thread is in privileged code that does not need to synchronize with the collector. This is a special state, similar to the IN_JNI state but requiring different interaction with the collector (as there is no JNI stack frame, the registers have to be saved in contextRegisters). As well, this state should only be entered from privileged code in the org.jikesrvm.scheduler package. Typically, this state is entered using a call to enterNative() just prior to idling the thread; though it would not be wrong to enter it prior to any other long-running activity that does not require interaction with the GC.

See Also:
Constant Field Values

IN_JNI

public static final int IN_JNI
Same as IN_NATIVE, except that we're executing JNI code and thus have a JNI stack frame and JNI environment, and thus the GC can load registers from there rather than using contextRegisters.

See Also:
Constant Field Values

IN_JAVA_TO_BLOCK

public static final int IN_JAVA_TO_BLOCK
thread is in Java code but is expected to block. the transition from IN_JAVA to IN_jAVA_TO_BLOCK happens as a result of an asynchronous call by the GC or any other internal VM code that requires this thread to perform an asynchronous activity (another example is the request to do an isync on PPC). the point is that we're waiting for the thread to reach a safe point and expect this to happen in bounded time; but if the thread were to escape to native we want to know about it. thus, transitions into native code while in the IN_JAVA_TO_BLOCK state result in a notification (broadcast on the thread's monitor) and a state change to BLOCKED_IN_NATIVE. Observe that it is always safe to conservatively change IN_JAVA to IN_JAVA_TO_BLOCK.

See Also:
Constant Field Values

BLOCKED_IN_NATIVE

public static final int BLOCKED_IN_NATIVE
thread is in native code, and is to block before returning to Java code. the transition from IN_NATIVE to BLOCKED_IN_NATIVE happens as a result of an asynchronous call by the GC or any other internal VM code that requires this thread to perform an asynchronous activity (another example is the request to do an isync on PPC). as well, code entering privileged code that would otherwise go from IN_JAVA to IN_NATIVE will go to BLOCKED_IN_NATIVE instead, if the state was IN_JAVA_TO_BLOCK.

the point of this state is that the thread is guaranteed not to execute any Java code until:

  1. The state changes to IN_NATIVE, and
  2. The thread gets a broadcast on its monitor.
Observe that it is always safe to conservatively change IN_NATIVE to BLOCKED_IN_NATIVE.

See Also:
Constant Field Values

BLOCKED_IN_JNI

public static final int BLOCKED_IN_JNI
like BLOCKED_IN_NATIVE, but indicates that the thread is in JNI rather than VM native code.

See Also:
Constant Field Values

TERMINATED

public static final int TERMINATED
Thread has died. As in, it's no longer executing any Java code and will never do so in the future. Once this is set, the GC will no longer mark any part of the thread as live; the thread's stack will be deleted. Note that this is distinct from the aboutToTerminate state.

See Also:
Constant Field Values

LAST_EXEC_STATUS

public static final int LAST_EXEC_STATUS
Not actually a state but just a marker.

See Also:
Constant Field Values

trampolineRegisters

private ArchitectureSpecific.Registers trampolineRegisters
Registers used by return barrier trampoline


hijackedReturnAddress

private Address hijackedReturnAddress
Return address of stack frame hijacked by return barrier


hijackedReturnCalleeFp

private Address hijackedReturnCalleeFp
Callee frame pointer for stack frame hijacked by return barrier


hijackedReturnCallerFp

private Address hijackedReturnCallerFp
Caller frame pointer for stack frame hijacked by return barrier


DEBUG_STACK_TRAMPOLINE

public static final boolean DEBUG_STACK_TRAMPOLINE
debugging flag for return barrier trampoline

See Also:
Constant Field Values

stackTrampolineBridgeInstructions

public static ArchitectureSpecific.CodeArray stackTrampolineBridgeInstructions
pointer to bridge code for return barrier trampoline


execStatus

private int execStatus
Thread state. Indicates if the thread is running, and if so, what mode of execution it is using (Java, VM native, or JNI)


isAboutToTerminate

private boolean isAboutToTerminate
Is the thread about to terminate? Protected by the thread's monitor. Note that this field is not set atomically with the entering of the thread onto the aboutToTerminate array - in fact it happens before that. When this field is set to true, the thread's stack will no longer be scanned by GC. Note that this is distinct from the TERMINATED state.


isBlocking

boolean isBlocking
Is this thread in the process of blocking?


isJoinable

boolean isJoinable
Is the thread no longer executing user code? Protected by the Java monitor associated with the Thread object.


next

RVMThread next
Link pointer for queues (specifically ThreadQueue). A thread can only be on one such queue at a time. The queue that a thread is on is indicated by queuedOn.


queuedOn

volatile ThreadQueue queuedOn
The queue that the thread is on, or null if the thread is not on a queue (specifically ThreadQueue). If the thread is on such a queue, the next field is used as a link pointer.


awaitingSpinLock

SpinLock awaitingSpinLock
Used to handle contention for spin locks


contenderLink

RVMThread contenderLink

thread

private Thread thread
java.lang.Thread wrapper for this Thread. Not final so it may be assigned during booting


name

private String name
Name of the thread (can be changed during execution)


daemon

protected boolean daemon
The virtual machine terminates when the last non-daemon (user) thread terminates.


priority

private int priority
Scheduling priority for this thread. Note that: Thread.MIN_PRIORITY <= priority <= Thread.MAX_PRIORITY.


threadSlot

public int threadSlot
Index of this thread in threadBySlot[]. This value must be non-zero because it is shifted and used in Object lock ownership tests.


lockingId

public int lockingId

systemThread

private final SystemThread systemThread
Non-null indicates this is a system thread, that is one used by the system and as such doesn't have a Runnable...


bootThread

public static RVMThread bootThread
The boot thread, can't be final so as to allow initialization during boot image writing.


threadingInitialized

public static boolean threadingInitialized
Is the threading system initialized?


timerTicks

public static long timerTicks
Number of timer ticks we've seen


yieldpointsTaken

private long yieldpointsTaken

yieldpointsTakenFully

private long yieldpointsTakenFully

nativeEnteredBlocked

private long nativeEnteredBlocked

jniEnteredBlocked

private long jniEnteredBlocked

disallowAllocationsByThisThread

private boolean disallowAllocationsByThisThread
Assertion checking while manipulating raw addresses -- see VM.disableGC()/VM.enableGC(). A value of "true" means it's an error for this thread to call "new". This is only used for assertion checking; we do not bother to set it when Configuration.VerifyAssertions is false.


disableGCDepth

private int disableGCDepth
Counts the depth of outstanding calls to VM.disableGC(). If this is set, then we should also have disallowAllocationsByThisThread set. The converse also holds.


barriersEntered

public int barriersEntered

barriersExited

public int barriersExited

stack

private byte[] stack
Execution stack for this thread.


stackLimit

public Address stackLimit
The Address of the guard area for stack.


framePointer

Address framePointer
FP for current frame, saved in the prologue of every method


hiddenSignatureId

int hiddenSignatureId
"hidden parameter" for interface invocation thru the IMT


arrayIndexTrapParam

int arrayIndexTrapParam
"hidden parameter" from ArrayIndexOutOfBounds trap to C trap handler


yieldToOSRRequested

public boolean yieldToOSRRequested
Is the next taken yieldpoint in response to a request to perform OSR?


yieldForCBSCall

public boolean yieldForCBSCall
Is CBS enabled for 'call' yieldpoints?


yieldForCBSMethod

public boolean yieldForCBSMethod
Is CBS enabled for 'method' yieldpoints?


numCBSCallSamples

public int numCBSCallSamples
Number of CBS samples to take in this window


countdownCBSCall

public int countdownCBSCall
Number of call yieldpoints between CBS samples


firstCBSCallSample

public int firstCBSCallSample
round robin starting point for CBS samples


numCBSMethodSamples

public int numCBSMethodSamples
Number of CBS samples to take in this window


countdownCBSMethod

public int countdownCBSMethod
Number of counter ticks between CBS samples


firstCBSMethodSample

public int firstCBSMethodSample
round robin starting point for CBS samples


codePatchSyncRequested

public boolean codePatchSyncRequested
flag indicating this processor needs to execute a memory synchronization sequence Used for code patching on SMP PowerPCs.


thread_cbs_counter

public int thread_cbs_counter
For builds using counter-based sampling. This field holds a processor-specific counter so that it can be updated efficiently on SMP's.


yieldpointsEnabledCount

private int yieldpointsEnabledCount
Should this thread yield at yieldpoints? A value of: 1 means "yes" (yieldpoints enabled) <= 0 means "no" (yieldpoints disabled)


yieldpointRequestPending

boolean yieldpointRequestPending
Is a takeYieldpoint request pending on this thread?


atYieldpoint

boolean atYieldpoint
Are we at a yieldpoint right now?


flushRequested

public boolean flushRequested
Is there a flush request for this thread? This is handled via a soft handshake.


softHandshakeRequested

public boolean softHandshakeRequested
Is a soft handshake requested? Logically, this field is protected by the thread's monitor - but it is typically only mucked with when both the thread's monitor and the softHandshakeDataLock are held.


softHandshakeLeft

public static int softHandshakeLeft
How many threads have not yet reached the soft handshake? (protected by softHandshakeDataLock)


softHandshakeDataLock

public static Monitor softHandshakeDataLock
Lock that protects soft handshake fields.


handshakeLock

public static Monitor handshakeLock
Lock that prevents multiple (soft or hard) handshakes from proceeding concurrently.


contextRegisters

public final ArchitectureSpecific.Registers contextRegisters
Place to save register state when this thread is not actually running.


contextRegistersShadow

private final ArchitectureSpecific.Registers contextRegistersShadow

contextRegistersSave

public final ArchitectureSpecific.Registers contextRegistersSave
Place to save register state when this thread is not actually running.


contextRegistersSaveShadow

private final ArchitectureSpecific.Registers contextRegistersSaveShadow

exceptionRegisters

private final ArchitectureSpecific.Registers exceptionRegisters
Place to save register state during hardware(C signal trap handler) or software (RuntimeEntrypoints.athrow) trap handling.


exceptionRegistersShadow

private final ArchitectureSpecific.Registers exceptionRegistersShadow

uncaughtExceptionCount

private int uncaughtExceptionCount
Count of recursive uncaught exceptions, we need to bail out at some point


cachedFreeLock

public Lock cachedFreeLock
A cached free lock. Not a free list; this will only ever contain 0 or 1 locks!


waitObject

protected Object waitObject
Place to save/restore this thread's monitor state during Object.wait() and Object.notify().


waitCount

protected int waitCount
Lock recursion count for this thread's monitor.


shouldSuspend

boolean shouldSuspend
Should the thread suspend?


shouldSuspendToken

int shouldSuspendToken
An integer token identifying the last suspend request


isSuspended

boolean isSuspended
Is the thread suspended?


shouldBlockForHandshake

boolean shouldBlockForHandshake
Should the thread block for handshake?


isBlockedForHandshake

boolean isBlockedForHandshake
Is the thread blocked for handshake?


shouldBlockForGC

boolean shouldBlockForGC
Should the thread block for a thread-to-thread communication?


isBlockedForGC

boolean isBlockedForGC
Is the thread blocked for thread-to-thread communication?


suspendBlockAdapter

public static final RVMThread.SuspendBlockAdapter suspendBlockAdapter

handshakeBlockAdapter

public static final RVMThread.HandshakeBlockAdapter handshakeBlockAdapter

gcBlockAdapter

public static final RVMThread.GCBlockAdapter gcBlockAdapter

blockAdapters

static final RVMThread.BlockAdapter[] blockAdapters

waiting

protected RVMThread.Waiting waiting
Accounting of whether or not a thread is waiting (in the Java thread state sense), and if so, how it's waiting.

Invariant: the RVM runtime does not ever use this field for any purpose other than updating it so that the java.lang.Thread knows the state. Thus, if you get sloppy with this field, the worst case outcome is that some Java program that queries the thread state will get something other than what it may or may not have expected.


asyncThrowable

Throwable asyncThrowable
Exception to throw in this thread at the earliest possible point.


hasInterrupt

boolean hasInterrupt
Has the thread been interrupted?


takeYieldpoint

public int takeYieldpoint
Should the next executed yieldpoint be taken? Can be true for a variety of reasons. See RVMThread.yieldpoint

To support efficient sampling of only prologue/epilogues we also encode some extra information into this field. 0 means that the yieldpoint should not be taken. >0 means that the next yieldpoint of any type should be taken <0 means that the next prologue/epilogue yieldpoint should be taken

Note the following rules:

  1. If takeYieldpoint is set to 0 or -1 it is perfectly safe to set it to 1; this will have almost no effect on the system. Thus, setting takeYieldpoint to 1 can always be done without acquiring locks.
  2. Setting takeYieldpoint to any value other than 1 should be done while holding the thread's monitor().
  3. The exception to rule (2) above is that the yieldpoint itself sets takeYieldpoint to 0 without holding a lock - but this is done after it ensures that the yieldpoint is deferred by setting yieldpointRequestPending to true.


timeSliceExpired

public int timeSliceExpired
How many times has the "timeslice" expired? This is only used for profiling and OSR (in particular base-to-opt OSR).


parkingPermit

private boolean parkingPermit
Is a running thread permitted to ignore the next park request


jniEnv

private JNIEnvironment jniEnv
Cached JNI environment for this thread


jniEnvShadow

private JNIEnvironment jniEnvShadow

physicalAllocationFailed

private boolean physicalAllocationFailed
Used by GC to determine collection success


collectionAttempt

private int collectionAttempt
Used by GC to determine collection success


outOfMemoryError

private static OutOfMemoryError outOfMemoryError
The OOME to throw


PROLOGUE

public static final int PROLOGUE
See Also:
Constant Field Values

BACKEDGE

public static final int BACKEDGE
See Also:
Constant Field Values

EPILOGUE

public static final int EPILOGUE
See Also:
Constant Field Values

NATIVE_PROLOGUE

public static final int NATIVE_PROLOGUE
See Also:
Constant Field Values

NATIVE_EPILOGUE

public static final int NATIVE_EPILOGUE
See Also:
Constant Field Values

OSROPT

public static final int OSROPT
See Also:
Constant Field Values

onStackReplacementEvent

public final Object onStackReplacementEvent
Only used by OSR when VM.BuildForAdaptiveSystem. Declared as an Object to cut link to adaptive system. Ugh.


isWaitingForOsr

public boolean isWaitingForOsr
The flag indicates whether this thread is waiting for on stack replacement before being rescheduled.


bridgeInstructions

public ArchitectureSpecific.CodeArray bridgeInstructions
Before call new instructions, we need a bridge to recover register states from the stack frame.


fooFPOffset

public Offset fooFPOffset
Foo frame pointer offset


tsFPOffset

public Offset tsFPOffset
Thread switch frame pointer offset


requesting_osr

public boolean requesting_osr
Flag to synchronize with osr organizer, the trigger sets osr requests the organizer clear the requests


osr_done

public boolean osr_done
Flag to indicate that the last OSR request is done.


availableProcessors

public static int availableProcessors
The number of processors to use.


pthread_id

public Word pthread_id
Thread handle. Currently stores pthread_t, which we assume to be no larger than a pointer-sized word.


scratchStorage

private double scratchStorage
Scratch area for use for gpr <=> fpr transfers by PPC baseline compiler. Used to transfer x87 to SSE registers on IA32


threadIdx

private int threadIdx
Current index of this thread in the threads array. This may be changed by another thread, but only while the acctLock is held.


systemShuttingDown

private static boolean systemShuttingDown
Is the system in the process of shutting down (has System.exit been called)


debugRequested

public static volatile boolean debugRequested
Flag set by external signal to request debugger activation at next thread switch. See also: RunBootImage.C


asyncDebugRequestedForThisThread

public volatile boolean asyncDebugRequestedForThisThread

doProfileReport

public static Latch doProfileReport
The latch for reporting profile data.


inDumpStack

protected int inDumpStack
Number of times dump stack has been called recursively


activeMutatorContext

public boolean activeMutatorContext
Is this a "registered mutator?"


dumpLock

public static Monitor dumpLock
Lock used for dumping stack and such.


exitInProgress

protected static boolean exitInProgress
In dump stack and dying


worldStopped

private static boolean worldStopped

traceDetails

protected static final boolean traceDetails
Extra debug from traces

See Also:
Constant Field Values

SHOW_FP_IN_STACK_DUMP

private static final boolean SHOW_FP_IN_STACK_DUMP
Toggle display of frame pointer address in stack dump

See Also:
Constant Field Values

PRIMORDIAL_THREAD_INDEX

public static final int PRIMORDIAL_THREAD_INDEX
Index of thread in which "VM.boot()" runs

See Also:
Constant Field Values

LOG_MAX_THREADS

public static final int LOG_MAX_THREADS
Maximum number of RVMThread's that we can support.

See Also:
Constant Field Values

MAX_THREADS

public static final int MAX_THREADS
See Also:
Constant Field Values

threadBySlot

public static RVMThread[] threadBySlot
thread array - all threads are stored in this array according to their threadSlot.


monitorBySlot

private static final NoYieldpointsMonitor[] monitorBySlot
Per-thread monitors. Note that this array is statically initialized. It starts out all null. When a new thread slot is allocated, a monitor is added for that slot.

Question: what is the outcome, if any, of taking a yieldpoint while holding this lock?

  1. If there is a GC request we will wait on this condition variable and thus release it. Someone else might then acquire the lock before realizing that there is a GC request and then do bad things.
  2. The yieldpoint might acquire another thread's monitor. Thus, two threads may get into lock inversion with each other.
  3. ???


communicationLockBySlot

private static final Monitor[] communicationLockBySlot

acctLock

public static NoYieldpointsMonitor acctLock
Lock (mutex) used for creating and destroying threads as well as thread accounting. This mutex should not be held while thread monitors (see monitorBySlot) are held. Use this mutex only to protect accesses to:


debugLock

public static NoYieldpointsMonitor debugLock
Lock (mutex) used for servicing debug requests.


outputLock

private static NoYieldpointsMonitor outputLock
Lock used for generating debug output.


aboutToTerminate

private static final int[] aboutToTerminate
Thread slots of threads that are about to terminate. This must be an int array because it's accessed from code that cannot have barriers.


aboutToTerminateN

private static int aboutToTerminateN
Number of threads that are about to terminate.


freeSlots

private static final int[] freeSlots
Free thread slots


freeSlotN

private static int freeSlotN
Number of free thread slots.


nextSlot

public static int nextSlot
When there are no thread slots on the free list, this is the next one to use.


numThreads

public static int numThreads
Number of threads in the system (some of which may not be active).


threads

public static final RVMThread[] threads
Packed and unordered array or active threads. Only entries in the range 0 to numThreads-1 (inclusive) are defined. Note that it should be possible to scan this array without locking and get all of the threads - but only if you scan downward and place a memory fence between loads.

Note further that threads remain in this array even after the Java libraries no longer consider the thread to be active.


handshakeThreads

public static final RVMThread[] handshakeThreads
Preallocated array for use in handshakes. Protected by handshakeLock.


debugThreads

public static final RVMThread[] debugThreads
Preallocated array for use in debug requested. Protected by debugLock.


numActiveThreads

private static int numActiveThreads
Number of active threads in the system.


numActiveDaemons

private static int numActiveDaemons
Number of active daemon threads.


feedlet

public Feedlet feedlet
The Feedlet instance for this thread to use to make addEvent calls.


allButGC

public static final RVMThread.AllButGCHardHandshakeVisitor allButGC

totalSuspendTime

static long totalSuspendTime

totalResumeTime

static long totalResumeTime

sloppyExecStatusHistogram

static final int[] sloppyExecStatusHistogram

statusAtSTWHistogram

static final int[] statusAtSTWHistogram

execStatusTransitionHistogram

static final int[] execStatusTransitionHistogram
Constructor Detail

RVMThread

public RVMThread(byte[] stack,
                 Thread thread,
                 String name,
                 boolean daemon,
                 SystemThread systemThread,
                 int priority)
Create a new RVM Thread

Parameters:
stack - The stack on which to execute the thread.
thread - The corresponding java.lang.Thread.
name - The name of the thread
daemon - True if this is a daemon thread.
systemThread - True if this is a system thread.
priority - The threads execution priority.

RVMThread

public RVMThread(SystemThread systemThread,
                 String name)
Create a thread with default stack and with the given name.


RVMThread

public RVMThread(SystemThread systemThread,
                 byte[] stack,
                 String name)
Create a thread with the given stack and name. Used by CollectorThread and the boot image writer for the boot thread.


RVMThread

public RVMThread(Thread thread,
                 long stacksize,
                 String name,
                 boolean daemon,
                 int priority)
Create a thread with ... called by java.lang.VMThread.create. System thread isn't set.

Method Detail

notRunning

public static boolean notRunning(int state)

getHijackedReturnCalleeFp

public Address getHijackedReturnCalleeFp()
Returns:
the callee frame pointer for the stack frame hijacked by the return barrier

getExecStatus

public int getExecStatus()

attemptFastExecStatusTransition

private boolean attemptFastExecStatusTransition(int oldState,
                                                int newState)

setExecStatus

private void setExecStatus(int newState)

getIsAboutToTerminate

public boolean getIsAboutToTerminate()

isOnQueue

public boolean isOnQueue()
Returns:
True if this thread is currently on a queue.

monitorForSlot

static NoYieldpointsMonitor monitorForSlot(int slot)
Get a NoYieldpointsCondLock for a given thread slot.


monitor

public NoYieldpointsMonitor monitor()
Get the NoYieldpointsCondLock for this thread.


communicationLockForSlot

public Monitor communicationLockForSlot(int slot)

communicationLock

public Monitor communicationLock()

init

public static void init()
Initialize the threading subsystem for the boot image.


assertAcceptableStates

public void assertAcceptableStates(int expected)

assertAcceptableStates

public void assertAcceptableStates(int expected1,
                                   int expected2)

assertUnacceptableStates

public void assertUnacceptableStates(int unexpected)

assertUnacceptableStates

public void assertUnacceptableStates(int unexpected1,
                                     int unexpected2)

bind

static void bind(int cpuId)

bindIfRequested

static void bindIfRequested()

boot

public static void boot()
Boot the threading subsystem.


addAboutToTerminate

private void addAboutToTerminate()
Add this thread to the termination watchlist. Called by terminating threads before they finish terminating.


processAboutToTerminate

public static void processAboutToTerminate()
Method called after processing a list of threads, or before starting a new thread. This does two things. First, it guarantees that the thread slots used by any dead threads are freed. Second, it guarantees that each thread deregisters itself from GC. Thus, it is essential that after requesting things like mutator flushes, you call this, to ensure that any threads that had died before or during the mutator flush request do the Right Thing.


assignThreadSlot

void assignThreadSlot()
Find a thread slot not in use by any other live thread and bind the given thread to it. The thread's threadSlot field is set accordingly.


releaseThreadSlot

void releaseThreadSlot()
Release a thread's slot in the threads array.


acknowledgeBlockRequests

private void acknowledgeBlockRequests()
Check if the thread has block requests (for example, for suspension and GC). If it does, clear the requests and marked the thread as blocked for that request. If there were any block requests, do a broadcast() on the thread's monitor(). This is an internal method and should only be called from code that implements thread blocking. The monitor() lock must be held for this method to work properly.


isBlocked

public boolean isBlocked()
Checks if the thread system has acknowledged that the thread is supposed to be blocked. This will return true if the thread is actually blocking, or if the thread is running native code but is guaranteed to block before returning to Java. Only call this method when already holding the monitor(), for two reasons:
  1. This method does not acquire the monitor() lock even though it needs to have it acquired given the data structures that it is accessing.
  2. You will typically want to call this method to decide if you need to take action under the assumption that the thread is blocked (or not blocked). So long as you hold the lock the thread cannot change state from blocked to not blocked.

Returns:
if the thread is supposed to be blocked

isInJava

public boolean isInJava()
Checks if the thread is executing Java code. A thread is executing Java code if its execStatus is IN_JAVA or IN_JAVA_TO_BLOCK, and if it is not aboutToTerminate, and if it is not blocked. Only call this method when already holding the monitor(), and probably only after calling setBlockedExecStatus(), for two reasons:
  1. This method does not acquire the monitor() lock even though it needs to have it acquired given the data structures that it is accessing.
  2. You will typically want to call this method to decide if you need to take action under the assumption that the thread is running Java (or not running Java). So long as you hold the lock - and you have called setBlockedExecStatus() - the thread cannot change state from running-Java to not-running-Java.

Returns:
if the thread is running Java

shouldBeSampled

public boolean shouldBeSampled()
Should the thread by eligible for sampling by the timer thread? Heuristically, we use timer-based sampling the in the adaptive system to determine where the program is spending time (and thus what to optimize). This doesn't have to be a 100% accurate, but it must be non-blocking and also closely approximate whether or not the thread is executing. For now, approximate just as being in JAVA. As a future item, we may want to actually correctly attribute time spent in native code to the top native method on the frame when the timer goes off. This will require work in the JNI enter/exit sequence to deal with timer samples appropriately.


checkBlockNoSaveContext

private void checkBlockNoSaveContext()
A variant of checkBlock() that does not save the thread state.


checkBlock

void checkBlock()
Check if the thread is supposed to block, and if so, block it. This method will ensure that soft handshake requests are acknowledged or else inhibited, that any blocking request is handled, that the execution state of the thread (execStatus) is set to IN_JAVA once all blocking requests are cleared, and that other threads are notified that this thread is in the middle of blocking by setting the appropriate flag (isBlocking). Note that this thread acquires the monitor(), though it may release it completely either by calling wait() or by calling unlockCompletely(). Thus, although it isn't generally a problem to call this method while holding the monitor() lock, you should only do so if the loss of atomicity is acceptable.

Generally, this method should be called from the following four places:

  1. The block() method, if the thread is requesting to block itself. Currently such requests only come when a thread calls suspend(). Doing so has unclear semantics (other threads may call resume() too early causing the well-known race) but must be supported because it's still part of the JDK. Why it's safe: the block() method needs to hold the monitor() for the time it takes it to make the block request, but does not need to continue to hold it when it calls checkBlock(). Thus, the fact that checkBlock() breaks atomicity is not a concern.
  2. The yieldpoint. One of the purposes of a yieldpoint is to periodically check if the current thread should be blocked. This is accomplished by calling checkBlock(). Why it's safe: the yieldpoint performs several distinct actions, all of which individually require the monitor() lock - but the monitor() lock does not have to be held contiguously. Thus, the loss of atomicity from calling checkBlock() is fine.
  3. The "WithHandshake" methods of HeavyCondLock. These methods allow you to block on a mutex or condition variable while notifying the system that you are not executing Java code. When these blocking methods return, they check if there had been a request to block, and if so, they call checkBlock(). Why it's safe: This is subtle. Two cases exist. The first case is when a WithHandshake method is called on a HeavyCondLock instance that is not a thread monitor(). In this case, it does not matter that checkBlock() may acquire and then completely release the monitor(), since the user was not holding the monitor(). However, this will break if the user is also holding the monitor() when calling the WithHandshake method on a different lock. This case should never happen because no other locks should ever be acquired when the monitor() is held. Additionally: there is the concern that some other locks should never be held while attempting to acquire the monitor(); the HeavyCondLock ensures that checkBlock() is only called when that lock itself is released. The other case is when a WithHandshake method is called on the monitor() itself. This should only be done when using your own monitor() - that is the monitor() of the thread your are running on. In this case, the WithHandshake methods work because: (i) lockWithHandshake() only calls checkBlock() on the initial lock entry (not on recursive entry), so atomicity is not broken, and (ii) waitWithHandshake() and friends only call checkBlock() after wait() returns - at which point it is safe to release and reacquire the lock, since there cannot be a race with broadcast() once we have committed to not calling wait() again.
  4. Any code following a potentially-blocking native call. Case (3) above is somewhat subsumed in this except that it is special due to the fact that it's blocking on VM locks. So, this case refers specifically to JNI. The JNI epilogues will call leaveJNIBlocked(), which calls a variant of this method.


enterNativeBlockedImpl

private void enterNativeBlockedImpl(boolean jni)
Internal method for transitioning a thread from IN_JAVA or IN_JAVA_TO_BLOCK to either BLOCKED_IN_NATIVE or BLOCKED_IN_JNI, depending on the value of the jni parameter. It is always safe to conservatively call this method when transitioning to native code, though it is faster to call either enterNative(), enterJNIFromCallIntoNative(), or enterJNIFromJNIFunctionCall().

This method takes care of all bookkeeping and notifications required when a a thread that has been requested to block instead decides to run native code. Threads enter native code never need to block, since they will not be executing any Java code. However, such threads must ensure that any system services (like GC) that are waiting for this thread to stop are notified that the thread has instead chosen to exit Java. As well, any requests to perform a sot handshake must be serviced and acknowledged.


leaveNativeBlockedImpl

private void leaveNativeBlockedImpl()

enterNativeBlocked

private void enterNativeBlocked()

leaveNativeBlocked

private void leaveNativeBlocked()

enterJNIBlocked

private void enterJNIBlocked()

leaveJNIBlocked

private void leaveJNIBlocked()

enterJNIBlockedFromJNIFunctionCall

public static void enterJNIBlockedFromJNIFunctionCall()

enterJNIBlockedFromCallIntoNative

public static void enterJNIBlockedFromCallIntoNative()

leaveJNIBlockedFromJNIFunctionCall

static void leaveJNIBlockedFromJNIFunctionCall()

leaveJNIBlockedFromCallIntoNative

public static void leaveJNIBlockedFromCallIntoNative()
Called when JNI code tried to transition from IN_JNI to IN_JAVA but failed


setBlockedExecStatus

private int setBlockedExecStatus()

block

int block(RVMThread.BlockAdapter ba,
          boolean asynchronous)
Attempt to block the thread, and return the state it is in after the attempt. If we're blocking ourselves, this will always return IN_JAVA. If the thread signals to us the intention to die as we are trying to block it, this will return TERMINATED. NOTE: the thread's execStatus will not actually be TERMINATED at that point yet.

Note that this method is ridiculously dangerous, especially if you pass asynchronous==false. Waiting for another thread to stop is not in itself interruptible - so if you ask another thread to block and they ask you to block, you might deadlock.


blockedFor

public boolean blockedFor(RVMThread.BlockAdapter ba)

asyncBlock

public int asyncBlock(RVMThread.BlockAdapter ba)

block

public int block(RVMThread.BlockAdapter ba)

beginPairWith

public void beginPairWith(RVMThread other)

endPairWith

public void endPairWith(RVMThread other)

beginPairWithCurrent

public void beginPairWithCurrent()

endPairWithCurrent

public void endPairWithCurrent()

safeBlock

private int safeBlock(RVMThread.BlockAdapter ba,
                      boolean asynchronous)

safeAsyncBlock

public int safeAsyncBlock(RVMThread.BlockAdapter ba)

safeBlock

public int safeBlock(RVMThread.BlockAdapter ba)

beginPairHandshake

public void beginPairHandshake()

endPairHandshake

public void endPairHandshake()

saveThreadState

public static void saveThreadState()
Save the current thread state. Call this prior to calling enterNative(). You must be in a method that is marked BaselineSaveLSRegisters.


enterNative

public static void enterNative()
Indicate that we'd like the current thread to be executing privileged code that does not require synchronization with the GC. This call may be made on a thread that is IN_JAVA or IN_JAVA_TO_BLOCK, and will result in the thread being either IN_NATIVE or BLOCKED_IN_NATIVE. In the case of an IN_JAVA_TO_BLOCK->BLOCKED_IN_NATIVE transition, this call will acquire the thread's lock and send out a notification to any threads waiting for this thread to reach a safepoint. This notification serves to notify them that the thread is in GC-safe code, but will not reach an actual safepoint for an indetermined amount of time. This is significant, because safepoints may perform additional actions (such as handling handshake requests, which may include things like mutator flushes and running isync) that IN_NATIVE code will not perform until returning to IN_JAVA by way of a leaveNative() call.


attemptLeaveNativeNoBlock

public static boolean attemptLeaveNativeNoBlock()
Attempt to transition from IN_JNI or IN_NATIVE to IN_JAVA, fail if execStatus is anything but IN_JNI or IN_NATIVE.

Returns:
true if thread transitioned to IN_JAVA, otherwise false

leaveNative

public static void leaveNative()
Leave privileged code. This is valid for threads that are either IN_NATIVE, IN_JNI, BLOCKED_IN_NATIVE, or BLOCKED_IN_JNI, and always results in the thread being IN_JAVA. If the thread was previously BLOCKED_IN_NATIVE or BLOCKED_IN_JNI, the thread will block until notified that it can run again.


enterJNIFromCallIntoNative

public static void enterJNIFromCallIntoNative()

leaveJNIFromCallIntoNative

public static void leaveJNIFromCallIntoNative()

enterJNIFromJNIFunctionCall

public static void enterJNIFromJNIFunctionCall()

leaveJNIFromJNIFunctionCall

public static void leaveJNIFromJNIFunctionCall()

unblock

public void unblock(RVMThread.BlockAdapter ba)

handleDebugRequestForThread

private void handleDebugRequestForThread()

checkDebugRequest

public static void checkDebugRequest()

timerTick

void timerTick()

yieldpointsEnabled

public boolean yieldpointsEnabled()
Are we allowed to take yieldpoints?


enableYieldpoints

public void enableYieldpoints()
Enable yieldpoints on this thread.


disableYieldpoints

public void disableYieldpoints()
Disable yieldpoints on this thread.


failIfYieldpointsDisabled

public void failIfYieldpointsDisabled()
Fail if yieldpoints are disabled on this thread


getCurrentThread

public static RVMThread getCurrentThread()
Returns:
The currently executing thread

getCurrentThreadSlot

public static int getCurrentThreadSlot()
Returns:
the unique slot of the currently executing thread

getThreadSlot

public int getThreadSlot()
Returns:
the slot of this thread

setupBootJavaThread

public void setupBootJavaThread()
Called during booting to give the boot thread a java.lang.Thread


toString

public String toString()
String representation of thread

Overrides:
toString in class Object

getJavaLangThread

public Thread getJavaLangThread()
Get the current java.lang.Thread.


getJNIEnv

public JNIEnvironment getJNIEnv()
Get current thread's JNI environment.


getDisableGCDepth

public int getDisableGCDepth()
Get the disable GC depth


setDisableGCDepth

public void setDisableGCDepth(int d)
Modify the disable GC depth


getDisallowAllocationsByThisThread

public boolean getDisallowAllocationsByThisThread()
Are allocations allowed by this thread?


setDisallowAllocationsByThisThread

public void setDisallowAllocationsByThisThread()
Disallow allocations by this thread


clearDisallowAllocationsByThisThread

public void clearDisallowAllocationsByThisThread()
Allow allocations by this thread


initializeJNIEnv

public void initializeJNIEnv()
Initialize JNI environment for system threads. Called by VM.finishBooting


hasNativeStackFrame

public boolean hasNativeStackFrame()
Indicate whether the stack of this Thread contains any C frame (used in RuntimeEntrypoints.deliverHardwareException for stack resize)

Returns:
false during the prolog of the first Java to C transition true afterward

run

public void run()
Method to be executed when this thread starts running. Calls java.lang.Thread.run but system threads can override directly.


startoff

private static void startoff()
Begin execution of current thread by calling its "run" method. This method is at the bottom of all created method's stacks.


start

public void start()
Start execution of 'this' by putting it on the appropriate queue of an unspecified virtual processor.


terminate

public void terminate()
Terminate execution of current thread by abandoning all references to it and resuming execution in some other (ready) thread.


callSystemExit

private void callSystemExit(int exitStatus)
Call System.exit() with the correct security status.

Parameters:
exitStatus -

terminateUnpreemptible

private void terminateUnpreemptible()
Unpreemptible portion of thread termination. Unpreemptible to avoid a dead thread from being scheduled.


finishThreadTermination

void finishThreadTermination()
Uninterruptible final portion of thread termination.


yieldpointFromPrologue

public static void yieldpointFromPrologue()
Yieldpoint taken in prologue.


yieldpointFromBackedge

public static void yieldpointFromBackedge()
Yieldpoint taken on backedge.


returnBarrier

public static void returnBarrier()
The return barrier.

The following code implements return barriers as described for Lisp by Yuasa http://www.yuasa.kuis.kyoto-u.ac.jp/~yuasa/ilc2002/index.html http://dx.doi.org/10.1109/ISORC.2005.45 and for Jikes RVM by Kumar et al http://dx.doi.org/10.1145/2398857.2384639

This code is executed when a method returns into a frame that has been hijacked by the return barrier mechanism. The return barrier trampoline will save state, execute this method, and then upon return from this method will transparently return into the frame that had been hijacked.

In this default implementation, the barrier reinstalls itself in the caller's frame thus incrementally moving the barrier down the stack.

The execution of this method is fragile. It is generally safest to call some other method from here that does the substantive work of the barrier.


installStackTrampolineBridge

public void installStackTrampolineBridge(Address targetFp)
Install the stack trampoline bridge at a given frame, hijacking that frame, saving the hijacked return address and callee fp in thread-local state to allow execution of the hijacked frame later.

Parameters:
targetFp - The frame to be hijacked.

deInstallStackTrampoline

public void deInstallStackTrampoline()
de-install the stack trampoline (disabling return barriers).


getStackTrampolineBridgeIP

private Address getStackTrampolineBridgeIP()
Returns:
the address of the stack trampoline bridge code

getTrampolineHijackedReturnAddress

public Address getTrampolineHijackedReturnAddress()
Returns:
the hijacked return address

isTrampolineIP

public static boolean isTrampolineIP(Address ip)
Determine whether a given method is the stack trampoline

Parameters:
ip - the code to be checked
Returns:
true if the code is the stack trampoline.

getHijackedReturnAddress

public static Address getHijackedReturnAddress(Address hijackedFp)
Given a frame that has been hijacked by the stack trampoline, return the real (hijacked) return address.

Parameters:
hijackedFp - a frame that has been hijacked by the stack trampoline
Returns:
the return address for the frame that was hijacked.

dumpFrame

private static void dumpFrame(Address fp)
Dump the specified frame in a format useful for debugging the stack trampoline

Parameters:
fp - The frame to be dumped.

getNextUnencounteredFrame

public Address getNextUnencounteredFrame()
Returns:
the caller of the frame in which the trampoline is installed (STACKFRAME_SENTINEL_FP by default)

yieldpointFromEpilogue

public static void yieldpointFromEpilogue()
Yieldpoint taken in epilogue.


suspend

public void suspend()
Suspend execution of current thread until it is resumed. Call only if caller has appropriate security clearance.


resume

public void resume()
Resume execution of a thread that has been suspended. Call only if caller has appropriate security clearance.


yieldNoHandshake

public static void yieldNoHandshake()

yieldWithHandshake

public static void yieldWithHandshake()

sleep

public static void sleep(long ns)
                  throws InterruptedException
Suspend execution of current thread for specified number of seconds (or fraction).

Throws:
InterruptedException

sleep

public static void sleep(long millis,
                         int ns)
                  throws InterruptedException
Suspend execution of current thread for specified number of seconds (or fraction).

Throws:
InterruptedException

waitImpl

void waitImpl(Object o,
              boolean hasTimeout,
              long whenWakeupNanos)

wait

public static void wait(Object o)
Support for Java Object.wait() synchronization primitive.

Parameters:
o - the object synchronized on

wait

public static void wait(Object o,
                        long millis)
Support for Java Object.wait() synchronization primitive.

Parameters:
o - the object synchronized on
millis - the number of milliseconds to wait for notification

waitAbsoluteNanos

public static void waitAbsoluteNanos(Object o,
                                     long whenNanos)
Support for RTSJ- and pthread-style absolute wait.

Parameters:
o - the object synchronized on
whenNanos - the absolute time in nanoseconds when we should wake up

raiseIllegalMonitorStateException

public static void raiseIllegalMonitorStateException(String msg,
                                                     Object o)

notify

public static void notify(Object o)
Support for Java Object.notify() synchronization primitive.

Parameters:
o - the object synchronized on

notifyAll

public static void notifyAll(Object o)
Support for Java synchronization primitive.

Parameters:
o - the object synchronized on
See Also:
Object.notifyAll()

stop

public void stop(Throwable cause)

park

public void park(boolean isAbsolute,
                 long time)
          throws Throwable
Throws:
Throwable

unpark

public void unpark()

getLockingId

public int getLockingId()
Get this thread's id for use in lock ownership tests. This is just the thread's slot as returned by getThreadSlot(), shifted appropriately so it can be directly used in the ownership tests.


snapshotHandshakeThreads

public static int snapshotHandshakeThreads(RVMThread.SoftHandshakeVisitor v)

softHandshake

public static void softHandshake(RVMThread.SoftHandshakeVisitor v)
Tell each thread to take a yieldpoint and wait until all of them have done so at least once. Additionally, call the visitor on each thread when making the yieldpoint request; the purpose of the visitor is to set any additional fields as needed to make specific requests to the threads that yield. Note that the visitor's visit() method is called with both the thread's monitor held, and the softHandshakeDataLock held.

Currently we only use this mechanism for code patch isync requests on PPC, but this mechanism is powerful enough to be used by sliding-views style concurrent GC.


softRendezvousCheckAndClear

public boolean softRendezvousCheckAndClear()
Check and clear the need for a soft handshake rendezvous. This method cannot do anything that leads to a write barrier or allocation.


softRendezvousCommit

public void softRendezvousCommit()
Commit the soft handshake rendezvous. This method cannot do anything that leads to a write barrier or allocation.


softRendezvous

public void softRendezvous()
Rendezvous with a soft handshake request. Can only be called when the thread's monitor is held.


handleHandshakeRequest

void handleHandshakeRequest()
Handle requests that required a soft handshake. May be called after we acknowledged the soft handshake. Thus - this is for actions in which it is sufficient for the thread to acknowledge that it plans to act upon the request in the immediate future, rather than that the thread acts upon the request prior to acknowledging.

This is almost always called with the monitor() lock held, but that's not guaranteed. If you need that lock, you can grab it (since it's a recursive lock). But you should avoid grabbing other sorts of locks since that might cause deadlock.


blockAllMutatorsForGC

public static void blockAllMutatorsForGC()
Stop all mutator threads. This is current intended to be run by a single thread. Fixpoint until there are no threads that we haven't blocked. Fixpoint is needed to catch the (unlikely) case that a thread spawns another thread while we are waiting.


unblockAllMutatorsForGC

public static void unblockAllMutatorsForGC()
Unblock all mutators blocked for GC.


hardHandshakeSuspend

public static void hardHandshakeSuspend(RVMThread.BlockAdapter ba,
                                        RVMThread.HardHandshakeVisitor hhv)

hardHandshakeResume

public static void hardHandshakeResume(RVMThread.BlockAdapter ba,
                                       RVMThread.HardHandshakeVisitor hhv)

hardHandshakeSuspend

public static void hardHandshakeSuspend()

hardHandshakeResume

public static void hardHandshakeResume()

worldStopped

public static boolean worldStopped()

yieldpoint

public static void yieldpoint(int whereFrom,
                              Address yieldpointServiceMethodFP)
Process a taken yieldpoint.


throwFromUninterruptible

private static void throwFromUninterruptible(Throwable e)

resizeCurrentStack

public static void resizeCurrentStack(int newSize,
                                      ArchitectureSpecific.Registers exceptionRegisters)
Change the size of the currently executing thread's stack.

Parameters:
newSize - new size (in bytes)
exceptionRegisters - register state at which stack overflow trap was encountered (null --> normal method call, not a trap)

transferExecutionToNewStack

private static void transferExecutionToNewStack(byte[] newStack,
                                                ArchitectureSpecific.Registers exceptionRegisters)

fixupMovedStack

public void fixupMovedStack(Offset delta)
This (suspended) thread's stack has been moved. Fixup register and memory references to reflect its new position.

Parameters:
delta - displacement to be applied to all interior references

adjustRegisters

private static void adjustRegisters(ArchitectureSpecific.Registers registers,
                                    Offset delta)
A thread's stack has been moved or resized. Adjust registers to reflect new position.

Parameters:
registers - registers to be adjusted
delta - displacement to be applied

adjustStack

private static void adjustStack(byte[] stack,
                                Address fp,
                                Offset delta)
A thread's stack has been moved or resized. Adjust internal pointers to reflect new position.

Parameters:
stack - stack to be adjusted
fp - pointer to its innermost frame
delta - displacement to be applied to all its interior references

copyStack

private static Offset copyStack(byte[] newStack)
Initialize a new stack with the live portion of the stack we're currently running on.
  lo-mem                                        hi-mem
                           |<---myDepth----|
                 +----------+---------------+
                 |   empty  |     live      |
                 +----------+---------------+
                  ˆmyStack   ˆmyFP           ˆmyTop
       +-------------------+---------------+
       |       empty       |     live      |
       +-------------------+---------------+
        ˆnewStack           ˆnewFP          ˆnewTop
 


makeDaemon

public void makeDaemon(boolean on)
Set the "isDaemon" status of this thread. Although a java.lang.Thread can only have setDaemon invoked on it before it is started, Threads can become daemons at any time. Note: making the last non daemon a daemon will terminate the VM.

Note: This method might need to be uninterruptible so it is final, which is why it isn't called setDaemon.

Public so that java.lang.Thread can use it.


dumpAll

public static void dumpAll(int verbosity)
Dump information for all threads, via VM.sysWrite(String). Each thread's info is newline-terminated.

Parameters:
verbosity - Ignored.

isBootThread

public boolean isBootThread()
Returns:
The value of isBootThread()

isMainThread

private boolean isMainThread()
Returns:
Is this the MainThread ?

isSystemThread

public boolean isSystemThread()
Is this a system thread?


getCollectorThread

public CollectorThread getCollectorThread()
Get the collector thread this RVMTHread is running


isDaemonThread

public boolean isDaemonThread()
Returns the value of daemon.


ignoreHandshakesAndGC

public boolean ignoreHandshakesAndGC()
Should this thread run concurrently with STW GC and ignore handshakes?


isAlive

public boolean isAlive()
Is the thread started and not terminated


setName

public void setName(String name)
Sets the name of the thread

Parameters:
name - the new name for the thread
See Also:
Thread.setName(String)

getName

public String getName()
Gets the name of the thread

See Also:
Thread.getName()

holdsLock

public boolean holdsLock(Object obj)
Does the currently running Thread hold the lock on an obj?

Parameters:
obj - the object to check
Returns:
whether the thread holds the lock
See Also:
Thread.holdsLock(Object)

isInterrupted

public boolean isInterrupted()
Was this thread interrupted?

Returns:
whether the thread has been interrupted
See Also:
Thread.isInterrupted()

clearInterrupted

public void clearInterrupted()
Clear the interrupted status of this thread

See Also:
Thread.interrupted()

interrupt

public void interrupt()
Interrupt this thread

See Also:
Thread.interrupt()

getPriority

public int getPriority()
Get the priority of the thread

Returns:
the thread's priority
See Also:
Thread.getPriority()

setPriority

public void setPriority(int priority)
Set the priority of the thread

Parameters:
priority -
See Also:
Thread.getPriority()

getState

public Thread.State getState()
Get the state of the thread in a manner compatible with the Java API

Returns:
thread state
See Also:
Thread.getState()

join

public void join(long ms,
                 int ns)
          throws InterruptedException
Wait for the thread to die or for the timeout to occur

Parameters:
ms - milliseconds to wait
ns - nanoseconds to wait
Throws:
InterruptedException

countStackFrames

public int countStackFrames()
Count the stack frames of this thread


getStackLength

public int getStackLength()
Returns:
the length of the stack

getStack

public byte[] getStack()
Returns:
the stack

getExceptionRegisters

public ArchitectureSpecific.Registers getExceptionRegisters()
Returns:
the thread's exception registers

getContextRegisters

public ArchitectureSpecific.Registers getContextRegisters()
Returns:
the thread's context registers (saved registers when thread is suspended by green-thread scheduler).

reportCollectionAttempt

public void reportCollectionAttempt()
Set the initial attempt.


getCollectionAttempt

public int getCollectionAttempt()
Set the initial attempt.


resetCollectionAttempts

public void resetCollectionAttempts()
Resets the attempts.


physicalAllocationFailed

public boolean physicalAllocationFailed()
Get the physical allocation failed flag.


setPhysicalAllocationFailed

public void setPhysicalAllocationFailed()
Set the physical allocation failed flag.


clearPhysicalAllocationFailed

public void clearPhysicalAllocationFailed()
Clear the physical allocation failed flag.


getOutOfMemoryError

public static OutOfMemoryError getOutOfMemoryError()
Returns the outstanding OutOfMemoryError.


getNumActiveThreads

public static int getNumActiveThreads()
Number of active threads in the system.


getNumActiveDaemons

public static int getNumActiveDaemons()
Number of active daemon threads.


handleUncaughtException

public void handleUncaughtException(Throwable exceptionObject)

handlePossibleRecursiveException

private void handlePossibleRecursiveException()
Handle the case of exception handling triggering new exceptions.


dumpThread

private static void dumpThread(RVMThread t)

dumpThreadArray

private static void dumpThreadArray(RVMThread[] array,
                                    int bound)

dumpThreadSlotArray

private static void dumpThreadSlotArray(int[] array,
                                        int bound)

dumpThreadArray

private static void dumpThreadArray(String name,
                                    RVMThread[] array,
                                    int bound)

dumpThreadSlotArray

private static void dumpThreadSlotArray(String name,
                                        int[] array,
                                        int bound)

dumpAcct

public static void dumpAcct()

extDump

public void extDump()

dump

public void dump()
Dump this thread's identifying information, for debugging, via VM.sysWrite(String). We do not use any spacing or newline characters. Callers are responsible for space-separating or newline-terminating output.


dumpWithPadding

public void dumpWithPadding(int leftJustify)
Dump this thread's identifying information, for debugging, via VM.sysWrite(String). We pad to a minimum of leftJustify characters. We do not use any spacing characters. Callers are responsible for space-separating or newline-terminating output.

Parameters:
leftJustify - minimum number of characters emitted, with any extra characters being spaces.

dump

public void dump(int verbosity)
Dump this thread's identifying information, for debugging, via VM.sysWrite(String). We do not use any spacing or newline characters. Callers are responsible for space-separating or newline-terminating output. This function avoids write barriers and allocation.

Parameters:
verbosity - Ignored.

dump

public int dump(char[] dest,
                int offset)
Dump this thread's info, for debugging. Copy the info about it into a destination char array. We do not use any spacing or newline characters. This function may be called during GC; it avoids write barriers and allocation. For this reason, we do not throw an IndexOutOfBoundsException.

Parameters:
dest - char array to copy the source info into.
offset - Offset into dest where we start copying
Returns:
1 plus the index of the last character written. If we were to write zero characters (which we won't) then we would return offset. This is intended to represent the first unused position in the array dest. However, it also serves as a pseudo-overflow check: It may have the value dest.length, if the array dest was completely filled by the call, or it may have a value greater than dest.length, if the info needs more than dest.length - offset characters of space. -1 if offset is negative.

dump

public int dump(char[] dest)
Dump this thread's info, for debugging. Copy the info about it into a destination char array. We do not use any spacing or newline characters.

This is identical to calling dump(char[],int) with an offset of zero.


dumpStats

static void dumpStats()
Dump statistics gather on operations


trace

public static void trace(String who,
                         String what)
Print out message in format "[j] (cez#td) who: what", where: j = java thread id z* = RVMThread.getCurrentThread().yieldpointsEnabledCount (0 means yieldpoints are enabled outside of the call to debug) t* = numActiveThreads d* = numActiveDaemons * parenthetical values, printed only if traceDetails = true)

We serialize against a mutex to avoid intermingling debug output from multiple threads.


trace

public static void trace(String who,
                         String what,
                         int howmany)
Print out message in format "p[j] (cez#td) who: what howmany", where: p = processor id j = java thread id c* = java thread id of the owner of threadCreationMutex (if any) e* = java thread id of the owner of threadExecutionMutex (if any) t* = numActiveThreads d* = numActiveDaemons * parenthetical values, printed only if traceDetails = true)

We serialize against a mutex to avoid intermingling debug output from multiple threads.


traceHex

public static void traceHex(String who,
                            String what,
                            int howmany)

trace

public static void trace(String who,
                         String what,
                         Address addr)

_trace

private static void _trace(String who,
                           String what,
                           int howmany,
                           boolean hex)

traceback

public static void traceback(String message)
Print interesting scheduler information, starting with a stack traceback.

Note: the system could be in a fragile state when this method is called, so we try to rely on as little runtime functionality as possible (eg. use no bytecodes that require RuntimeEntrypoints support).


traceback

public static void traceback(String message,
                             int number)

tracebackWithoutLock

static void tracebackWithoutLock()

dumpStack

public static void dumpStack()
Dump stack of calling thread, starting at callers frame


dumpStack

public static void dumpStack(Address fp)
Dump state of a (stopped) thread's stack.

Parameters:
fp - address of starting frame. first frame output is the calling frame of passed frame

dumpStack

public static void dumpStack(Address ip,
                             Address fp)
Dump state of a (stopped) thread's stack.

Parameters:
ip - instruction pointer for first frame to dump
fp - frame pointer for first frame to dump

isAddressValidFramePointer

private static boolean isAddressValidFramePointer(Address address)
Return true if the supplied address could be a valid frame pointer. To check for validity we make sure the frame pointer is in one of the spaces;

or it is StackframeLayoutConstants.STACKFRAME_SENTINEL_FP. The STACKFRAME_SENTINEL_FP is possible when the thread has been created but has yet to be scheduled.

Parameters:
address - the address.
Returns:
true if the address could be a frame pointer, false otherwise.

showPrologue

private static void showPrologue(Address fp)

showMethod

private static void showMethod(int compiledMethodId,
                               Address fp)
Show a method where getCompiledMethod returns null

Parameters:
compiledMethodId -
fp -

showMethod

private static void showMethod(String name,
                               Address fp)
Show a method that we can't show (ie just a text description of the stack frame

Parameters:
name -
fp -

showMethod

private static void showMethod(RVMMethod method,
                               int lineNumber,
                               Address fp)
Helper function for dumpStack(Address,Address). Print a stack frame showing the method.


dumpStackAndDie

public static void dumpStackAndDie(Address fp)
Dump state of a (stopped) thread's stack and exit the virtual machine.

Parameters:
fp - address of starting frame Returned: doesn't return. This method is called from RunBootImage.C when something goes horrifically wrong with exception handling and we want to die with useful diagnostics.

safeToForceGCs

public static boolean safeToForceGCs()
Is it safe to start forcing garbage collects for stress testing?


gcEnabled

public static boolean gcEnabled()
Is it safe to start forcing garbage collects for stress testing?


setupBootThread

public static RVMThread setupBootThread()
Set up the initial thread and processors as part of boot image writing

Returns:
the boot thread

dumpVirtualMachine

public static void dumpVirtualMachine()
Dump state of virtual machine.


getCurrentFeedlet

public static Feedlet getCurrentFeedlet()

reportThreadTransitionCounts

public static void reportThreadTransitionCounts()

dump1DHisto

static void dump1DHisto(String name,
                        int[] histo)

observeExecStatus

void observeExecStatus()

observeExecStatusAtSTW

public static void observeExecStatusAtSTW(int execStatus)

transitionHistogramIndex

static int transitionHistogramIndex(int oldState,
                                    int newState)

observeStateTransition

static void observeStateTransition(int oldState,
                                   int newState)