There are a number of command-line options and environmentvariables that can affect the performance characteristics of theJava HotSpot Virtual Machine. Some of these options are consumed bythe launcher (such as ‘’ or‘’),some are processed by the launcher and passed to the JVM, whilemost are consumed directly by the JVM.
There are three main categories of options: standard options,non-standard options, and developer options. Standard options areexpected to be accepted by all JVM implementations and are stablebetween releases (though they can be deprecated). Options thatbegin with arenon-standard (not guaranteed to be supported on all JVMimplementations), and are subject to change without notice insubsequent releases of the Java SDK. Options that begin with are developeroptions and often have specific system requirements for correctoperation and may require privileged access to system configurationparameters; they are not recommended for casual use. These optionsare also subject to change without notice.
Command-line flags control the values of internal variables inthe JVM, all of which have a type and a default value. For booleanvalues, the mere presence or lack of presence of a flag on thecommand-line can control the value of the variables. For boolean flags, a‘’ or'' prefix before thename indicates a true or false value, respectively. For variablesthat require additional data, there are a number of differentmechanisms used to pass that data in. Some flags accept the datapassed in directly after the name of the flag without anydelineator, while for other flags you have to separate the flagname from the data with a ‘’ or a ‘’ character. Unfortunatelythe method depends on the particular flag and its parsingmechanism. Developer flags (the flags) appear in only threedifferent forms: , , and .
Most all of the options that take an integer size value willaccept ‘’,‘’, or‘’ suffixeswhich are used a kilo-, mega-, or giga- multipliers for the number.These are most often used for arguments that control memorysizes.
The following sections gives an overview of the general purposejava launcher pertaining to the lifecyle of the HotSpot VM.
There are several HotSpot VM launchers in the Java StandardEdition, the general purpose launcher typically used is the javacommand on Unix and on Windows java and javaw commands, not to beconfused with javaws which is a network based launcher.
The launcher operations pertaining to VM startup are:
The most important phases are the andthese are described in the next sections.
The JNI invocation method performs the following:
This method can be called from the launcher to tear down the VM,it can also be called by the VM itself when a very serious erroroccurs.
The tear down of the VM takes the following steps:
The Java Hotspot VM supports class loading as defined by theJava Language Specification, Third Edition [1], the Java VirtualMachine Specification (JVMS), Second Edition [2] and as amended bythe updated JVMS chapter 5, Loading, Linking and Initializing[3].
The VM is responsible for resolving constant pool symbols, whichrequires loading, linking and then initializing classes andinterfaces. We will use the term “class loading” todescribe the overall process of mapping a class or interface nameto a class object, and the more specific terms loading, linking andinitializing for the phases of class loading as defined by theJVMS.
The most common reason for class loading is during bytecoderesolution, when a constant pool symbol in the classfile requiresresolution. Java APIs such as,, reflection APIs, and can initiate class loading. The VMitself can initiate class loading. The VM loads core classes suchas,, etc. at JVM startup. Loading aclass requires loading all superclasses and superinterfaces. Andclassfile verification, which is part of the linking phase, canrequire loading additional classes.
The VM and Java SE class loading libraries share theresponsibility for class loading. The VM performs constant poolresolution, linking and initialization for classes and interfaces.The loading phase is a cooperative effort between the VM andspecific class loaders ().
The load class phase takes a class or interface name, finds thebinary in classfile format, defines the class and creates the object. The load class phase canthrow a error if a binary representationcan not be found. In addition, the load class phase does formatchecking on the syntax of the classfile, which can throw a or. Prior to completingloading of a class, the VM must load all of its superclasses andsuperinterfaces. If the class hierarchy has a problem such thatthis class is its own superclass or superinterface (recursively),then the VM will throw a. The VM also throws if the directsuperinterface is not an interface, or the direct superclass is aninterface.
The link class phase first does verification, which checks theclassfile semantics, checks the constant pool symbols and does typechecking. These checks can throw a. Linking then does preparation, whichcreates and initializes static fields to standard defaults andallocates method tables. Note that no Java code has yet been run.Linking then optionally does resolution of symbolic references.
Class initialization runs the static initializers, andinitializers for static fields. This is the first Java code whichruns for this class. Note that class initialization requiressuperclass initialization, although not superinterfaceinitialization.
The JVMS specifies that class initialization occurs on the first“active use” of a class. The JLS allows flexibility inwhen the symbolic resolution step of linking occurs as long as werespect the semantics of the language, finish each step of loading,linking and initializing before performing the next step, and throwerrors when programs would expect them. For performance, theHotSpot VM generally waits until class initialization to load andlink a class. So if classreferences class,loading classwill not necessarily cause loading of class(unless required for verification). Execution of the firstinstruction that referenceswill cause initialization of,which requires loading and linking of class.
When a class loader is asked to find and load a class, it canask another class loader to do the actual loading. This is calledclass loader delegation. The first loader is an initiating loader,and the class loading that ultimately defines the class is calledthe defining loader. In the case of bytecode resolution, theinitiating loader is the class loader for the class whose constantpool symbol we are resolving.
Class loaders are defined hierarchically and each class loaderhas a delegation parent. The delegation defines a search order forbinary class representations. The Java SE class loader hierarchysearches the bootstrap class loader, the extension class loader andthe system class loader in that order. The system class loader isthe default application class loader, which runs “main”and loads classes from the classpath. The application class loadercan be a class loader from the Java SE class loader libraries, orit can be provided by an application developer. The Java SE classloader libraries implement the extension class loader which loadsclasses from the lib/ext directory of the JRE.
The VM implements the bootstrap class loader, which loadsclasses from the , including for examplert.jar. For faster startup, the VM can also process preloadedclasses via Class Data Sharing.
A class or interface name is defined as a fully qualified namewhich includes the package name. A class type is uniquelydetermined by that fully qualified name and the class loader. So aclass loader defines a namespace, and the same class name loaded bytwo distinct defining class loaders results in two distinct classtypes.
Given the existence of custom class loaders, the VM isresponsible for ensuring that non-well-behaved class loaders cannot violate type safety. See Dynamic Class Loading in the JavaVirtual Machine [4], and the JVMS 5.3.4 [2]. The VM ensures thatwhen classcalls,’s class loader and’s class loader agree on’s parameters and return value, bytracking and checking loader constraints.
Class loading creates either anor an in the GC permanent generation. TheinstanceKlass refers to a java mirror, which is the instance ofmirroring this class. The VM C++ access to theis via a.
The HotSpot VM maintains three main hash tables to track classloading. The contains loaded classes, whichmaps a class name/class loader pair to a. The contains both classname/initiating loader pairs and class name/defining loader pairs.Entries are currently only removed at a safepoint. The contains classes which arecurrently being loaded. It is used for checking and for parallelclass loading for class loaders that support multi-threadedclassloading. The tracks constraints for typesafety checking.
These hash tables are all protected by the. In general the load classphase in the VM is serialized using the Class loader objectlock.
’
is thrown. The code for thisverification step is present in theexternal library, and uses JNI to gather whatever information isneeded about classes and types.
. The consists of a number of stack mapframes, each which indicates the types of the items on theexpression stack and in the local variables at some offset in themethod. The JVM needs to then only perform one pass through thebytecode to verify the correctness of the types to verify thebytecode. This is the method already used by JavaME CLDC. Since itit smaller and faster, this method of verification is builtdirectly in the VM itself.
attributes will be present and thenew verifier will be used. Because of the possibility of olderexternal tools that might instrument the bytecode but neglect toupdate the attribute, certain verificationerrors that occur during type-checking verification may failover tothe type-inference method. Should that pass succeed, the class filewill be verified.
Class data sharing (CDS) is a feature introduced in J2SE 5.0that is intended to reduce the startup time for Java programminglanguage applications, in particular smaller applications, as wellas reduce footprint. When the JRE is installed on 32-bit platformsusing the Sun provided installer, the installer loads a set ofclasses from the system jar file into a private internalrepresentation, and dumps that representation to a file, called a“shared archive”. If the Sun JRE installer is not beingused, this can be done manually, as explained below. Duringsubsequent JVM invocations, the shared archive is memory-mapped in,saving the cost of loading those classes and allowing much of theJVM's metadata for these classes to be shared among multiple JVMprocesses.
Class data sharing is supported only with the Java HotSpotClient VM, and only with the serial garbage collector.
The primary motivation for including CDS is the decrease instartup time it provides. CDS produces better results for smallerapplications because it eliminates a fixed cost: that of loadingcertain core classes. The smaller the application relative to thenumber of core classes it uses, the larger the saved fraction ofstartup time.
The footprint cost of new JVM instances has been reduced in twoways. First, a portion of the shared archive, currently betweenfive and six megabytes, is mapped read-only and therefore sharedamong multiple JVM processes. Previously this data was replicatedin each JVM instance. Second, since the shared archive containsclass data in the form in which the Java Hotspot VM uses it, thememory which would otherwise be required to access the originalclass information in is not needed. These savingsallow more applications to be run concurrently on the same machine.On Microsoft Windows, the footprint of a process, as measured byvarious tools, may appear to increase, because a larger number ofpages are being mapped in to the process' address space. This isoffset by the reduction in the amount of memory (inside MicrosoftWindows) which is needed to hold portions on.Reducing footprint remains a high priority.
In HotSpot, the class data sharing implementation introduces newSpaces into the permanent generation which contain the shared data.The classes.jsa shared archive is memory mapped into these Spacesat VM startup. Subsequently, the shared region is managed by theexisting VM memory management subsystem.
Read-only shared data includes constant method objects(), symbol objects (),and arrays of primitives, mostly character arrays.
Read-write shared data consists of mutable method objects(), constant pool objects (), VM internal representation ofJava classes and arrays (es andes), and various,, and objects.
The current HotSpot interpreter, which is used for executingbytecodes, is a template based interpreter. The HotSpot runtimea.k.a. generates an interpreter inmemory at the startup using the information in the(assembly code corresponding to each bytecode). A template is adescription of each bytecode. Thedefines all the templates and provides accessor functions to getthe template for a given bytecode. The non-product flag can be usedto view the template table generated in memory during the VM'sstartup process.
The template design performs better than a classicswitch-statement loop for several reasons. First, the switchstatement performs repeated compare operations, and in the worstcase it may be required to compare a given command with all but onebytecodes to locate the required one. Second, it uses a separatesoftware stack to pass Java arguments, while the native C stack isused by the VM itself. A number of JVM internal variables, such asthe program counter or the stack pointer for a Java thread, arestored in C variables, which are not guaranteed to be always keptin the hardware registers. Management of these software interpreterstructures consumes a considerable share of total executiontime.[5]
Overall, the gap between the VM and the real machine issignificantly narrowed by the HotSpot interpreter, which makes theinterpretation speed considerably higher. This, however, comes at aprice of e.g. large machine-specific chunks of code (roughly about10 KLOC (thousand lines of code) of Intel-specific and 14 KLOC ofSPARC-specific code). Overall code size and complexity is alsosignificantly higher, since e.g. the code supporting dynamic codegeneration is needed. Obviously, debugging dynamically generatedmachine code is significantly more difficult than static code.These properties certainly do not facilitate implementation ofruntime evolution, but they don’t make it infeasibleeither.[5]
The interpreter calls out to the VM runtime for complexoperations (basically anything too complicated to do in assemblylanguage) such as constant pool lookup.
The HotSpot interpreter is also a critical part of the overallHotSpot adaptive optimization story. Adaptive optimization solvesthe problems of JIT compilation by taking advantage of aninteresting program property. Virtually all programs spend the vastmajority of their time executing a minority of their code. Ratherthan compiling method by method, just in time, the Java HotSpot VMimmediately runs the program using an interpreter, and analyzes thecode as it runs to detect the critical hot spots in the program.Then it focuses the attention of a global native-code optimizer onthe hot spots. By avoiding compilation of infrequently executedcode (most of the program), the Java HotSpot compiler can devotemore attention to the performance-critical parts of the program,without necessarily increasing the overall compilation time. Thishot spot monitoring is continued dynamically as the program runs,so that it literally adapts its performance on the fly to theuser's needs.
Java virtual machines use exceptions to signal that a programhas violated the semantic constraints of the Java language. Forexample, an attempt to index outside the bounds of an array willcause an exception. An exception causes a non-local transfer ofcontrol from the point where the exception occurred (or wasthrown) to a point specified by the programmer (or where theexception iscaught).[6]
The HotSpot interpreter, dynamic compilers, and runtime allcooperate to implement exception handling. There are two generalcases of exception handling: either the exception is thrown andcaught in the same method, or it's caught by a caller. The lattercase is more complicated and requiresstack unwinding tofind the appropriate handler.
Exceptions can be initiated by thethrow bytecode, areturn from a VM-internal call, a return from a JNI call, or areturn from a Java call. (The last case is really just a laterstage of the first 3.) When the VM recognizes that an exception hasbeen thrown, the runtime system is invoked to find the nearesthandler for that exception. Three pieces of information are used tofind the handler; the current method, the current bytecode, and theexception object. If a handler is not found in the current method,as mentioned above, the current activation stack frame is poppedand the process is iteratively repeated for previous frames.
Once the correct handler is found, the VM execution state isupdated, and we jump to the handler as Java code execution isresumed.
Broadly, we can define “synchronization” as amechanism that prevents, avoids or recovers from the inopportuneinterleavings (commonly called “races”) of concurrentoperations. In Java, concurrency is expressed through the threadconstruct. Mutual exclusion is a special case of synchronizationwhere at most a single thread is permitted access to protected codeor data.
HotSpot provides Java monitors by which threads runningapplication code may participate in a mutual exclusion protocol. Amonitor is either locked or unlocked, and only one thread may ownthe monitor at any one time. Only after acquiring ownership of amonitor may a thread enter the critical section protected by themonitor. In Java, critical sections are referred to as"synchronized blocks", and are delineated in code by thestatement.
If a thread attempts to lock a monitor and the monitor is in anunlocked state, the thread will immediately gain ownership of themonitor. If a subsequent thread attempts to gain ownership of themonitor while the monitor is locked that thread will not bepermitted to proceed into the critical section until the ownerreleases the lock and the 2nd thread manages to gain (or isgranted) exclusive ownership of the lock.
Some additional terminology: to “enter” a monitormeans to acquire exclusive ownership of the monitor and enter theassociated critical section. Likewise, to “exit” amonitor means to release ownership of the monitor and exit thecritical section. We also say that a thread that has locked amonitor now “owns” that monitor.“Uncontended” refers to synchronization operations onan otherwise unowned monitor by only a single thread.
The HotSpot VM incorporates leading-edge techniques for bothuncontended and contended synchronization operations which boostsynchronization performance by a large factor.
Uncontended synchronization operations, which comprise themajority of synchronizations, are implemented with constant-timetechniques. Withbiased locking, in the best case theseoperations are essentially free of cost. Since most objects arelocked by at most one thread during their lifetime, we allow thatthread tobias an object toward itself. Once biased, thatthread can subsequently lock and unlock the object withoutresorting to expensive atomic instructions.[7]
Contended synchronization operations use advanced adaptivespinning techniques to improve throughput even for applicationswith significant amounts of lock contention. As a result,synchronization performance becomes so fast that it is not asignificant performance issue for the vast majority of real-worldprograms.
In HotSpot, most synchronization is handled through what we call””fast-path” code. We have two just-in-timecompilers (JITs) and an interpreter, all of which will emitfast-path code. The two JITs are “C1”, which is the compiler, and“C2”, which is the compiler. C1 and C2 bothemit fast-path code directly at the synchronization site. In thenormal case when there's no contention, the synchronizationoperation will be completed entirely in the fast-path. If, however,we need to block or wake a thread (in monitorenter or monitorexit,respectively), the fast-path code will call into the slow-path. Theslow-path implementation is in native C++ code while the fast-pathis emitted by the JITs.
Per-object synchronization state is encoded in the first word(the so-calledmark word) of the VM's object representation.For several states, the mark word is multiplexed to point toadditional synchronization metadata. (As an aside, in addition, themark word is also multiplexed to contain GC age data, and theobject's identity hashCode value.) The states are:
Thread management covers all aspects of the thread lifecycle,from creation through to termination, and the coordination ofthreads within the VM. This involves management of threads createdfrom Java code (whether application code or library code), nativethreads that attach directly to the VM, or internal VM threadscreated for a range of purposes. While the broader aspects ofthread management are platform independent, the details necessarilyvary depending on the underlying operating system.
The basic threading model in Hotspot is a 1:1 mapping betweenJava threads (an instance of) and native operating systemthreads. The native thread is created when the Java thread isstarted, and is reclaimed once it terminates. The operating systemis responsible for scheduling all threads and dispatching to anyavailable CPU.
The relationship between Java thread priorities and operatingsystem thread priorities is a complex one that varies acrosssystems. These details are covered later.
There are two basic ways for a thread to be introduced into theVM: execution of Java code that calls on a object; or attaching an existingnative thread to the VM using JNI. Other threads created by the VMfor internal purposes are discussed below.
There are a number of objects associated with a given thread inthe VM (remembering that Hotspot is written in the C++object-oriented programming language):
When ais started the VM creates the associatedand objects, and ultimately the nativethread. After preparing all of the VM state (such as thread-localstorage and allocation buffers, synchronization objects and soforth) the native thread is started. The native thread completesinitialization and then executes a start-up method that leads tothe execution of the object's method, and then, upon its return,terminates the thread after dealing with any uncaught exceptions,and interacting with the VM to check if termination of this threadrequires termination of the whole VM. Thread termination releasesall allocated resources, removes the from the set of knownthreads, invokes destructors for the and and ultimately ceases execution whenits initial startup method completes.
A native thread attaches to the VM using the JNI call. In response to this anassociated andinstance is created and basic initialization is performed. Next a object must be created for theattached thread, which is done by reflectively invoking the Javacode for the class constructor, based on the argumentssupplied when the thread attached. Once attached, a thread caninvoke whatever Java code it needs to via the other JNI methodsavailable. Finally when the native thread no longer wishes to beinvolved with the VM it can call the JNI method to disassociate itfrom the VM (release resources, drop the reference to the instance, destruct the andobjects and so forth).
A special case of attaching a native thread is the initialcreation of the VM via the JNIcall, which can be done by a native application or by the launcher(). This causes arange of initialization operations to take place and then actseffectively as if a call to was made. The thread can theninvoke Java code as needed, such as reflective invocation of the method of an application. See the JNIsection for further details.
The VM uses a number of different internal thread states tocharacterize what each thread is doing. This is necessary both forcoordinating the interactions of threads, and for providing usefuldebugging information if things go wrong. A thread's statetransitions as different actions are performed, and thesetransition points are used to check that it is appropriate for athread to proceed with the requested action at that point in time– see the discussion of safepoints below.
The main thread states from the VM perspective are asfollows:
For debugging purposesadditional state information is also maintained for reporting bytools, in thread dumps, stack traces etc. This is maintained intheand some of it has fallen into dis-use, butstates reported in thread dumps etc include:
Other subsystems andlibraries impose their own state information, such as the JVMTIsystem and theexposed by theclass itself. Such informationis generally not accessible to, nor relevant to, the management ofthreads inside the VM.
People are often surprised to discover that even executing asimple “Hello World” program can result in the creationof a dozen or more threads in the system. These arise from acombination of internal VM threads, and library related threads(such as reference handler and finalizer threads). The main kindsof VM threads are as follows:
All threads are instances of the class,and all threads that execute Java code areinstances (a subclass of). TheVM keeps track of all threads in a linked-list known as the, and which is protected by the – one of the keysynchronization locks used within the VM.
The spends its time waiting for operationsto appear in the, and then executing thoseoperations. Typically these operations are passed on to the because they require that the VM reach asafepoint before they can be executed. In simple terms, whenthe VM is at safepoint all threads inside the VM have been blocked,and any threads executing in native code are prevented fromreturning to the VM while the safepoint is in progress. This meansthat the VM operation can be executed knowing that no thread can bein the middle of modifying the Java heap, and all threads are in astate such that their Java stacks are unchanging and can beexamined.
The most familiar VM operation is for garbage collection, ormore specifically for the “stop-the-world” phase ofgarbage collection that is common to many garbage collectionalgorithms. But many other safepoint based VM operations exist, forexample: biased locking revocation, thread stack dumps, threadsuspension or stopping (i.e. The method) and numerousinspection/modification operations requested through JVMTI.
Many VM operations are synchronous, that is the requestor blocksuntil the operation has completed, but some are asynchronous orconcurrent, meaning that the requestor can proceed in parallel withthe (assuming no safepoint is initiated ofcourse).
Safepoints are initiated using a cooperative, polling-basedmechanism. In simple terms, every so often a thread asks“should I block for a safepoint?”. Asking this questionefficiently is not so simple. One place where the question is oftenasked is during a thread state transition. Not all statetransitions do this, for example a thread leaving the VM to go tonative code, but many do. The other places where a thread asks arein compiled code when returning from a method or at certain stagesduring loop iteration. Threads executing interpreted code don'tusually ask the question, instead when the safepoint is requestedthe interpreter switches to a different dispatch table thatincludes the code to ask the question; when the safepoint is over,the dispatch table is switched back again. Once a safepoint hasbeen requested, the must wait until all threads are known tobe in a safepoint-safe state before proceeding to execute the VMoperation. During a safepoint theis used to block any threads that were running, with the finally releasing theafter the VM operation has been performed.
In addition to the Java heap, which is maintained by the Javaheap manager and garbage collectors, HotSpot also uses the C/C++heap (also called the malloc heap) for storage of VM-internalobjects and data. A set of C++ classes derived from the base class is used to manage C++ heapoperations.
and its subclasses provide a fastallocation layer that sits on top of malloc/free. Eachallocates memory blocks (or) out of 3 globals. Eachsatisfies allocation requests for a distinct range of allocationsizes. For example, a request for 1k of memory will be allocatedfrom the “small”,while a 10K allocation will be made from the "medium".This is done to avoid wasteful memory fragmentation.
The system also provides better performancethan pure malloc/free. The latter operations may requireacquisition of global OS locks, which affects scalability and canhurt performance.s are thread-local objects which cache acertain amount of storage, so that in the fast-path allocation casea lock is not required. Likewise, freeoperations do not require a lock in the common case.
s are used for thread-local resourcemanagement () and handle management(). They are also used by boththe client and server compilers during compilation.
The JNI is a native programming interface. It allows Java codethat runs inside a Java virtual machine to interoperate withapplications and libraries written in other programming languages,such as C, C++, and assembly.
While applications can be written entirely in Java, there aresituations where Java alone does not meet the needs of anapplication. Programmers use the JNI to writeJava nativemethods to handle those situations when an application cannotbe written entirely in Java.
JNI native methods can be used to create, inspect,and update Java objects, call Java methods, catch and throwexceptions, load classes and obtain class information, and performruntime type checking.
The JNI may also be used with theInvocation API toenable an arbitrary native application to embed the Java VM. Thisallows programmers to easily make their existing applicationsJava-enabled without having to link with the VM source code.[9]
First, Java applications that depend on the JNI can no longerreadily run on multiple host environments. Even though the part ofan application written in the Java programming language is portableto multiple host environments, it will be necessary to recompilethe part of the application written in native programminglanguages.
Second, while the Javaprogramming language is type-safe and secure, native languages suchas C or C++ are not. As a result, Java developers must use extracare when writing applications using the JNI. A misbehaving nativemethod can corrupt the entire application. For this reason, Javaapplications are subject to security checks before invoking JNIfeatures.
A command line option, , is provided to aid indebugging problems in JNI usage by native methods. Specifying causes analternate set of debugging interfaces to be used by JNI calls. Thealternate interface verifies arguments to JNI calls morestringently, as well as performing additional internal consistencychecks.
HotSpot must take special care to keep track of which threadsare currently executing in native methods. During some VMactivities, notably some phases of garbage collection, one or morethreads must be halted at asafepoint in order to guaranteethat the Java memory heap is not modified during the sensitiveactivity. When we wish to bring a thread executing in native codeto a safepoint, it is allowed to continue executing native code,but the thread will be stopped when it attempts to return into Javacode or make a JNI call.
It is very important to provide easy ways to handle fatal errorsfor any software. Java Virtual Machine, i.e. JVM is not anexception. A typical fatal error would be. Another common fatal error onWindows is called error which is equivalent to on Solaris/Linux platforms. It is critical tounderstand the cause of these kind of fatal errors in order to fixthem either in your application or sometimes, in JVM itself.
Usually when JVM crashes on a fatal error, it will dump ahotspot error log file called , (where is replaced bythe crashed java process id) to the Windows desktop or the currentapplication directory on Solaris/Linux. Several enhancements havebeen made to improve the diagnosability of this file since JDK 6and many of them have been back ported to the JDK-1.4.2_09 release.Here are some highlights of these improvements:
Another important feature is you can specify " to the java command so that whenever VMcrashes, it will execute a list of commands you specified withinthe quotes shown above. A typical usage of this feature is you caninvoke the debugger such as dbx or Windbg to look into the crashwhen that happens. For the earlier releases, you can specify
as aruntime option so that when VM crashes, you can attach the runningJava process to your favorite debugger.
Having said something about HotSpot error log files, here is abrief summary on how JVM internally handles fatal errors.
Since is so common to some large scaleapplications, it is critical to provide useful diagnostic messageto users so that they could quickly identify a solution, sometimesby just specifying a larger Java heap size. When happens, the error message willindicate which type of memory is problematic. For example, it couldbe Java heap space or PermGen space etc. Since JDK 6, a stack tracewill be included in the error message. Also,
option was invented sothat a command will be run when the first OutOfMemoryError isthrown. Another nice feature that is worth mentioning is a built-inheap dump at OutOfMemoryError. It is enabled by specifyingoption and you can also tell the VM where to put the heap dump fileby specifying
.
Even though applications are carefully written to avoiddeadlocks, sometimes it still happens. When deadlock occurs, youcan type “Ctrl+Break” on Windows or grab the Javaprocess id and send SIGQUIT to the hang process on Solaris/Linux. AJava level stack trace will be dumped out to the standard out sothat you can analyze the reasons of deadlock. Since JDK 6, thisfeature has been built into jconsole which is a very useful tool inthe JDK. So when the application hangs on a deadlock, use jconsoleto attach the process and it will analyze which lock isproblematic. Most of the time, the deadlock is caused by acquiringlocks in the wrong order.
We strongly encourage you to check out the“Trouble-Shooting and Diagnostic Guide”[11]. Itcontains a lot of information which might be very useful todiagnose fatal errors.
“Resolving the Mysteries of Java SE Classloader”, JeffNisewanger, Karen Kinnear, JavaOne 2006.
[1] Java Language Specification, ThirdEdition. Gosling, Joy, Steele, Bracha.http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.2
[2] Java Virtual Machine Specification,Second Edition. Tim Lindholm, Frank Yellin.http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html
[3] Amendment to Java Virtual MachineSpecification. Chapter 5: Loading, Linking and Initializing.http://java.sun.com/docs/books/vmspec/2nd-edition/ConstantPool.pdf
[4] Dynamic Class Loading in the Java VirtualMachine. Shen Liang, Gilad Bracha. Proc. of the ACM Conf. onObject-Oriented Programming, Systems, Languages and Applications,October 1998http://www.bracha.org/classloaders.ps
[5] “Safe Clsss and Data Evolution inLarge and Long-Lived Java Applications”, Mikhail Dmitriev,http://research.sun.com/techrep/2001/smli_tr-2001-98.pdf
[6] Java Language Specification, ThirdEdition. Gosling, Joy, Steele, Bracha.http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html
[7] “Biased Locking in HotSpot”.http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot
[8] “Let’s say you’reinterested in using HotSpot as a vehicle for synchronizationresearch ...”.http://blogs.oracle.com/dave/entry/lets_say_you_re_interested
[9] “Java Native InterfaceSpecifications”http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/jniTOC.html
[10] “The Java Native InterfaceProgrammer’s Guide and Specification”, Sheng Liang,http://java.sun.com/docs/books/jni/html/titlepage.html
[11] “Trouble-Shooting and DiagnosticGuide”https://docs.oracle.com/en/java/javase/21/troubleshoot/troubleshooting-guide.pdf