Troubleshooting Guide
Troubleshooting Guide
Troubleshooting Guide
Release 23
F95954-01
September 2024
Java Platform, Standard Edition Troubleshooting Guide, Release 23
F95954-01
This software and related documentation are provided under a license agreement containing restrictions on use and
disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or
allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit,
perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation
of this software, unless required by law for interoperability, is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you find
any errors, please report them to us in writing.
If this is software, software documentation, data (as defined in the Federal Acquisition Regulation), or related
documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then
the following notice is applicable:
U.S. GOVERNMENT END USERS: Oracle programs (including any operating system, integrated software, any
programs embedded, installed, or activated on delivered hardware, and modifications of such programs) and Oracle
computer documentation or other Oracle data delivered to or accessed by U.S. Government end users are "commercial
computer software," "commercial computer software documentation," or "limited rights data" pursuant to the applicable
Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, reproduction,
duplication, release, display, disclosure, modification, preparation of derivative works, and/or adaptation of i) Oracle
programs (including any operating system, integrated software, any programs embedded, installed, or activated on
delivered hardware, and modifications of such programs), ii) Oracle computer documentation and/or iii) other Oracle
data, is subject to the rights and limitations specified in the license contained in the applicable contract. The terms
governing the U.S. Government's use of Oracle cloud services are defined by the applicable contract for such services.
No other rights are granted to the U.S. Government.
This software or hardware is developed for general use in a variety of information management applications. It is not
developed or intended for use in any inherently dangerous applications, including applications that may create a risk of
personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all
appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its
affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.
Oracle®, Java, MySQL, and NetSuite are registered trademarks of Oracle and/or its affiliates. Other names may be
trademarks of their respective owners.
Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used
under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Epyc, and the AMD logo
are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open
Group.
This software or hardware and documentation may provide access to or information about content, products, and
services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all
warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an
applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss,
costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth
in an applicable agreement between you and Oracle.
Contents
Preface
Audience xii
Documentation Accessibility xii
Diversity and Inclusion xii
Related Documents xii
Conventions xiii
2 Diagnostic Tools
Diagnostic Tools Overview 2-1
JDK Mission Control 2-2
Troubleshoot with JDK Mission Control 2-3
Flight Recorder 2-3
Produce a Flight Recording 2-4
Start a Flight Recording 2-5
Use Triggers for Automatic Flight Recordings 2-6
Use Startup Flags at the Command Line to Produce a Flight Recording 2-7
Analyze a Flight Recording 2-8
Analyze a Flight Recording Using JMC 2-8
Analyze a Flight Recording Using the jfr tool or JFR APIs 2-10
The jcmd Utility 2-12
Useful Commands for the jcmd Utility 2-14
Troubleshoot with the jcmd Utility 2-14
Native Memory Tracking 2-15
iii
How to Monitor VM Internal Memory 2-15
Use NMT to Detect a Memory Leak 2-20
NMT Memory Categories 2-20
JConsole 2-21
Troubleshoot with the JConsole Tool 2-21
Monitor Local and Remote Applications with JConsole 2-23
The jdb Utility 2-24
Troubleshoot with the jdb Utility 2-25
The jinfo Utility 2-25
Troubleshooting with the jinfo Utility 2-26
The jmap Utility 2-27
Heap Configuration and Usage 2-27
Heap Histogram 2-28
Class Loader Statistics 2-30
The jps Utility 2-32
The jrunscript Utility 2-32
The jstack Utility 2-32
Troubleshoot with the jstack Utility 2-33
Stack Trace from a Core Dump 2-33
Mixed Stack 2-33
The jstat Utility 2-36
The visualgc Tool 2-37
Control+Break Handler 2-38
Thread Dump 2-39
Thread States for a Thread Dump 2-40
Detect Deadlocks 2-40
Heap Summary 2-41
Native Operating System Tools 2-42
Troubleshooting Tools Based on the Operating System 2-42
Probe Providers in Java HotSpot VM 2-43
Custom Diagnostic Tools 2-44
The [Link] Package 2-44
The [Link] Package 2-45
The [Link] Class 2-45
JVM Tool Interface 2-45
Java Platform Debugger Architecture 2-45
Postmortem Diagnostic Tools 2-46
Hung Processes Tools 2-47
Monitoring Tools 2-47
Other Tools, Options, Variables, and Properties 2-48
The jstatd Daemon 2-49
iv
3 Troubleshoot Memory Leaks
The [Link] Error 3-1
Detecting a Memory Leak 3-4
JConsole 3-4
JDK Mission Control 3-6
Garbage Collection logs 3-7
Diagnosing Java Memory Leaks 3-8
Diagnostic Data 3-8
Heap Histograms 3-8
Heap Dumps 3-10
Java Flight Recordings 3-10
Class Loader Statistics 3-12
Analysis Tools 3-13
Heap Dump Analysis Tools 3-13
JDK Mission Control (JMC) 3-13
The jfr tool 3-14
NetBeans Profiler 3-17
Diagnosing Native Memory Leaks 3-17
Tracking All Memory Allocation and Free Calls 3-17
Native Memory Leaks for Allocations performed by the JVM 3-18
Native Memory Leaks from Outside the JVM 3-20
Tracking All Memory Allocations in the JNI Library 3-23
Monitoring the Objects Pending Finalization 3-24
Troubleshooting a Crash Instead of a [Link] error 3-24
v
Code Execution Performance 4-10
Use [Link] and [Link] Events to Monitor Code Execution
Performance 4-10
vi
Part III Debug Core Library Issues
11 AWT
Debug Tips for AWT 11-1
Layout Manager Issues 11-2
Key Events 11-2
Modality Issues 11-2
AWT Crashes 11-3
Focus Events 11-4
How to Trace Focus Events 11-4
Native Focus System 11-5
Focus Models Supported by X Window Managers 11-6
Miscellaneous Problems with Focus 11-6
vii
Data Transfer 11-8
Debug Drag-and-Drop Applications 11-8
Frequent Issues with Data Transfer 11-8
Other Issues 11-10
Splash Screen Issues 11-11
Tray Icon Issues 11-11
Pop-up Menu Issues 11-11
Background or Foreground Color Inheritance 11-11
AWT Panel Size Restriction 11-12
Hangs During Debugging of Pop-up Menus and Similar Components on X11 11-12
[Link]()/toBack() Behavior on X11 11-12
Heavyweight or Lightweight Components Mix 11-13
13 Java 2D
Generic Performance Issues 13-1
Hardware-Accelerated Rendering Primitives 13-1
Primitive Tracing to Detect and Avoid Non-Accelerated Rendering 13-2
Causes of Poor Rendering Performance 13-3
Improve Performance of Software-only Rendering 13-5
Text-Related Issues 13-5
Application Crash During Text Rendering 13-6
Differences in Text Appearance 13-7
Font Metrics 13-8
Java 2D Printing 13-8
viii
14 Swing
General Debug Tips for Swing 14-1
Specific Debug Tips for Swing 14-2
Incorrect Threading 14-2
JComponent Children Overlap 14-3
Display Update 14-3
Model Change 14-4
Add or Remove Components 14-4
Opaque Override 14-4
Permanent Changes to Graphics 14-4
Custom Painting and Double Buffering 14-5
Opaque Content Pane 14-5
Renderer Call for Each Cell Performance 14-5
Possible Leaks 14-5
Mix Heavyweight and Lightweight Components 14-5
Use Synth 14-6
Track Activity on Event Dispatch Thread 14-6
Specify Default Layout Manager 14-6
Listener Object Dispatched to Incorrect Component 14-6
Add a Component to Content Pane 14-6
Drag and Drop Support 14-7
One Parent for a Component 14-7
JFileChooser Issues with Windows Shortcuts 14-7
15 Internationalization
Troubleshoot Internationalization and Localization 15-1
16 Java Sound
Troubleshoot Java Sound Issues 16-1
ix
Operating System Details 17-3
Java SE Version 17-3
Command-Line Options 17-3
Environment Variables 17-4
Fatal Error Log 17-4
Core and Crash Dump 17-5
Logs and Traces 17-5
Report a Bug 17-5
Collect Core Dumps 17-5
Collect Core Dumps on Linux 17-6
Reasons for Not Getting a Core File 17-6
Collect Crash Dumps on Windows 17-7
Part VI Appendices
B Java 2D Properties
Properties on Linux B-1
Properties on Windows B-2
Properties on macOS B-2
D Command-Line Options
Java HotSpot VM Command-Line Options D-1
Other Command-Line Options D-5
x
E Summary of Tools in This Release
xi
Preface
Preface
This document helps you to troubleshoot issues with Java Platform, Standard Edition (Java
SE) applications. This document provides a description of the available tools and command-
line options that can help to analyze problems. This document also provides guidance about
debugging core library and client issues and describes some general issues, such as crashes,
hangs, and memory leaks. Finally, this document provides directions for data collection and
bug report preparation.
Audience
The target audience for this document include developers and application maintainers who use
the Java Development Kit (JDK), which is Oracle's implementation of Java SE. Most of the
information in this document can be applied to current and previous releases.
This document is intended for readers with a high-level understanding of the components of
the Java HotSpot VM, as well as some understanding of concepts such as garbage collection,
threads, and native libraries. It is also assumed that the reader is reasonably proficient with the
operating system where the Java application is developed and run.
Documentation Accessibility
For information about Oracle's commitment to accessibility, visit the Oracle Accessibility
Program website at [Link]
Related Documents
For more information about Java SE and relevant technologies, visit Java SE at a Glance.
xii
Preface
Conventions
The following text conventions are used in this document:
Convention Meaning
boldface Boldface type indicates graphical user interface elements associated with an
action, or terms defined in text or the glossary.
italic Italic type indicates book titles, emphasis, or placeholder variables for which
you supply particular values.
monospace Monospace type indicates commands within a paragraph, URLs, code in
examples, text that appears on the screen, or text that you enter.
xiii
Part I
General Java Troubleshooting
This part describes general Java troubleshooting techniques and contains the following topics.
• Prepare Java for Troubleshooting
Provides guidelines for setting up both Java and a Java application for better
troubleshooting techniques. These proactive Java setups help debug and narrow down
issues with Java and a Java application.
• Diagnostic Tools
Describes various diagnostic and monitoring tools used with Java Development Kit (JDK).
Further describes the troubleshooting tools available and explains custom tools
development using application programming interfaces (APIs).
• Troubleshoot Memory Leaks
Provides suggestions for diagnosing problems involving possible memory leaks.
• Troubleshoot Performance Issues Using Flight Recorder
Identifies performance issues with a Java application and debugs issues using the Java
Flight Recorder.
• Troubleshoot Security APIs
Provides a link to debug Java security issues.
1
Prepare Java for Troubleshooting
This section provides some guidelines for setting up both Java and a Java application for
easier troubleshooting. These proactive steps enable the collection of useful data and help
define problems arising from an application.
Topics
• Update the Java Runtime
• Enable Options and Flags for JVM Troubleshooting
• Make a Java Application Easier to Debug
• Gather Relevant Data
Note:
Depending on your situation or circumstances, it might not be possible to update or
upgrade to the latest Java SE version.
Note:
Core files may take up a lot of disk space depending on the memory usage of the
application.
1-1
Chapter 1
Enable Options and Flags for JVM Troubleshooting
Core files provide detailed information about the state of an application at the time of a
crash. They're not always useful in diagnosing a problem but are invaluable when they are
needed. Because crashes are often difficult to reproduce, having application core files
enabled can save time and provide valuable information. It's up to your and your
organization to decide whether your system can meet the potential space requirements.
2. Add -XX:+HeapDumpOnOutOfMemoryError to the JVM flags: The -
XX:+HeapDumpOnOutOfMemoryError flag saves a Java heap dump to disk if the applications
runs into an OutOfMemoryError.
A heap dump provides information on that portion of an application's memory usage that is
managed by the JVM directly. Like core files, heap dumps can be very large. A heap dump
can identify if part of an application is growing out of proportion to the rest, which may
cause an OutOfMemoryError.
3. Run a continuous flight recording: Set up Java to run with a continuous flight recording.
Continuous flight recordings provide a file-based record of JVM events. This provides a
low-overhead means of monitoring a Java application that can be used in the event of an
issue. See Produce a Flight Recording for how to setup such recordings.
4. Add the -Xlog:gc* command-line option: The -Xlog:gc option prints detailed information
about garbage collection, which helps diagnose problems with application performance
and memory management.
See Enable Logging with the JVM Unified Logging Framework in the java command
documentation for more information about this option and other information that the JVM
Unified Logging Framework can print.
Note:
Creating a discrete garbage collection log file makes it easier to read. It also
persists after a crash or application restart. Setting up log rotation enables you to
manage the amount of information retained and for how long. See -Xlog Output
in the java command documentation for how to do this.
5. Print Java version and JVM flags: Oracle Support, and even forums, ask for the exact
Java version your application uses and its JVM flags.
Run java -version at a command line to obtain the default Java version of your system. If
your application starts with a script, read through it and any associated configuration files
to find out if your application is using something other than the default Java version.
Alternatively, add -XX:PrintFlagsFinal and -showversion to your application's JVM
arguments, restart your application, and read the application logs for the results.
6. Set up Java Management Extensions (JMX) for remote monitoring: JMX is a
framework for monitoring Java applications. It's typically used through tools like Mission
Control or VisualVM. Ensuring that the application is open to remote monitoring helps if
you don't have direct access to the application or its system. There is no overhead for
opening up JMX to remote access. To do this, add
[Link]=portNum to the application's JVM flags, and then
restart your application. See Monitoring and Management Using JMX Technology in Java
Platform, Standard Edition Monitoring and Management Guide for details.
1-2
Chapter 1
Make a Java Application Easier to Debug
1-3
2
Diagnostic Tools
The Java Development Kit (JDK) provides diagnostic tools and troubleshooting tools specific to
various operating systems. Custom diagnostic tools can also be developed using the APIs
provided by the JDK.
This chapter contains the following sections:
• Diagnostic Tools Overview
• JDK Mission Control
• Flight Recorder
• The jcmd Utility
• Native Memory Tracking
• JConsole
• The jdb Utility
• The jinfo Utility
• The jmap Utility
• The jps Utility
• The jrunscript Utility
• The jstack Utility
• The jstat Utility
• The visualgc Tool
• Control+Break Handler
• Native Operating System Tools
• Custom Diagnostic Tools
• Postmortem Diagnostic Tools
• Hung Processes Tools
• Monitoring Tools
• Other Tools, Options, Variables, and Properties
• The jstatd Daemon
2-1
Chapter 2
JDK Mission Control
operating systems, and release. Frequently, only a subset of the tools is applicable to a given
issue at a particular time. Command-line options that are prefixed with -XX are specific to Java
HotSpot VM. See Java HotSpot VM Command-Line Options.
Note:
The -XX options are not part of the Java API and can vary from one release to the
next.
The tools and options are divided into several categories, depending on the type of problem
that you are troubleshooting. Certain tools and options might fall into more than one category.
• Postmortem diagnostics These tools and options can be used to diagnose a problem
after an application crashes. See Postmortem Diagnostic Tools.
• Hung processes These tools can be used to investigate a hung or deadlocked process.
See Hung Processes Tools.
• Monitoring These tools can be used to monitor a running application. See Monitoring
Tools.
• Other These tools and options can be used to help diagnose other issues. See Other
Tools, Options, Variables, and Properties.
Note:
Some command-line utilities described in this section are experimental. The jstack,
jinfo, and jmap utilities are examples of utilities that are experimental. It is
suggested to use the latest diagnostic utility, jcmd instead of the earlier jstack,
jinfo, and jmap utilities.
JMC is not part of the regular JDK installation. For more information on JMC downloads and
documentation, see JDK Mission Control Page.
JMC consists of :
• JVM Browser shows running Java applications and their JVMs.
• JMX Console is a mechanism for monitoring and managing JVMs. It connects to a running
JVM, collects, displays its characteristics in real time, and enables you to change some of
its runtime properties through Managed Beans (MBeans). You can also create rules that
trigger on certain events (for example, send an e-mail if the CPU usage by the application
reaches 90 percent).
• Flight Recorder (JFR) is a tool for collecting diagnostic and profiling data about a running
Java application. It is integrated into the JVM and causes very small performance
overhead, so it can be used in production environments. JFR continuously saves large
2-2
Chapter 2
Flight Recorder
amounts of data about the running applications. This profiling information includes thread
samples, lock profiles, and garbage collection details. JFR presents diagnostic information
in logically grouped tables and charts. It enables you to select the range of time and level
of detail necessary to focus on the problem. Data collected by JFR can be essential when
contacting Oracle support to help diagnose issues with your Java application.
• Plug-ins help in heap dump analysis and DTrace recording. See Plug-in Details. Java SE
plug-ins connect to a JVM using the Java Management Extensions (JMX) agent. For more
information about JMX, see the Java Platform, Standard Edition Java Management
Extensions Guide .
Flight Recorder
Flight Recorder (JFR) is a profiling and event collection framework built into the JDK.
Flight Recorder allows Java administrators and developers to gather detailed low-level
information about how a JVM and Java applications are behaving. You can use JMC to
visualize the data collected by JFR. Flight Recorder and JMC together create a complete
toolchain to continuously collect low-level and detailed runtime information enabling after-the-
fact incident analysis.
The advantages of using JFR are:
• It records data about JVM events as they occur, with a timestamp.
• Recording events with JFR enables you to preserve the execution states to analyze
issues. You can access the data anytime to better understand problems and resolve them.
• JFR can record a large amount of data on production systems while keeping the overhead
of the recording process low.
2-3
Chapter 2
Flight Recorder
• It is most suited for recording latencies. It records situations where the application is not
executing as expected and provide details on the bottlenecks.
• It provides insight into how programs interact with execution environment as a whole,
ranging from hardware, operating systems, JVM, JDK, and the Java application
environment.
Flight recordings can be started when the application is started or while the application is
running. The data is recorded as time-stamped data points called events. Events are
categorized as follows:
• Duration events: occurs at a particular duration with specific start time and stop time.
• Instant events: occurs instantly and gets logged immediately, for example, a thread gets
blocked.
• Sample events: occurs at regular intervals to check the overall health of the system, for
example, printing heap diagnostics every minute.
• Custom events: user defined events created using JMC or APIs.
In addition, there are predefined events that are enabled in a recording template. Some
templates only save very basic events and have virtually no impact on performance. Other
templates may come with slight performance overhead and may also trigger garbage
collections to gather additional data. The following templates are provided with Flight Recorder
in the <JDK_ROOT>/lib/jfr directory:
2-4
Chapter 2
Flight Recorder
Note:
Expand the node in the JVM Browser to view the recordings that are running.
Right-click any of the recordings to dump, dump whole, dump last part, edit, stop,
or close the recording. Stopping a profiling recording will still produce a recording
file and closing a profiling recording will discard the recording.
2-5
Chapter 2
Flight Recorder
Note:
You can set up JMC to automatically start a flight recording if a condition is met using
the Triggers tab in the JMX console. For more information, see Use Triggers for
Automatic Flight Recordings.
Note:
You can either select the Trigger when condition is met or Trigger when
recovering from condition check box.
6. Select what action you would like your rule to perform when triggered and click Next. For
example, choose Start Time Limited Flight Recording and browse the file destination
and recording time. Select the Open automatically checkbox, if you wish to open the flight
recording automatically when it is triggered.
7. Select constraints for your rule and click Next. For example, select the particular dates,
days of the week, or time of day when the rule should be active.
8. Enter a name for your rule and click Finish.
The rule is added to the My Rules list.
When you select your rule from the Trigger Rules list, the Rule Details pane displays its
components in the following tabs. You can edit the conditions, attributes, and constraints if you
wish:
• Condition
• Action
• Constraint
2-6
Chapter 2
Flight Recorder
Note:
When you actually dump the recording, you specify a new location for the
dumped file, so the files in the repository are only temporary.
2-7
Chapter 2
Flight Recorder
Note:
You can select a respective entry in the Outline view to navigate between the pages
of the automated analysis.
2-8
Chapter 2
Flight Recorder
Lock Instances
Lock instances provides further details on threads specifying the lock information, that is, if the
thread is trying to take a lock or waiting for a notification on a lock. If a thread has taken any
lock, the details are shown in the stack trace.
Memory
One way to detect problems with application performance to is to see how it uses memory
during runtime.
In the Memory page, the graph represents heap memory usage of the Java application. Each
cycle consists of a Java heap growth phase that represents the period of heap memory
allocations, followed by a short drop that represents garbage collection, and then the cycle
starts over. The important inference from the graph is that the memory allocations are short-
lived as garbage collector pushes down the heap to the start position at each cycle.
Select the Garbage Collection check box to see the garbage collection pause time in the
graph. It indicates that the garbage collector stopped the application during the pause time to
do its work. Long pause times lead to poor application performance, which needs to be
addressed.
Select the Alloc Total check box to see how much memory is allocated per second. You can
also view this as a percentage value in the Total Allocation (%) column.
Method Profiling
Method Profiling page enables you to see how often a specific method is run and for how
long it takes to run a method. The bottlenecks are determined by identifying the methods that
take a lot of time to execute.
As profiling generates a lot of data, it is not turned on by default. Start a new recording and
select Profiling - on server in the Event settings drop-down menu. Do a time fixed recording
for a short duration. JFR dumps the recording to the file name specified. Open the Method
Profiling page in JMC to see the top allocations. Top packages and classes are displayed.
Verify the details in the stack trace. Inspect the code to verify if the memory allocation is
concentrated on a particular object. JFR points to the particular line number where the problem
persists.
JVM Internals
The JVM Internals page provides detailed information about the JVM and its behavior.
2-9
Chapter 2
Flight Recorder
One of the most important parameters to observe is Garbage Collections. Garbage collection
is a process of deleting unused objects so that the space can be used for allocation of new
objects. The Garbage Collections page helps you to better understand the system behavior
and garbage collection performance during runtime.
The graphs shows the heap usage as compared to the pause times and how it varies during
the specified period. The page also lists all the garbage collection events that occurred during
the recording. Observe the longest pause times against the heap. The pause time indicates
that garbage collections are taking longer during application processing. It implies that garbage
collections are freeing less space on the heap. This situation can lead to memory leaks.
For effective memory management, see the Compilations page, which provides details on
code compilation along with duration. In large applications, you may have many compiled
methods, and memory can be exhausted, resulting in performance issues.
The TLAB Allocations page provides information about all object allocations. It provides
information about Allocations in TLAB and Allocations outside TLAB. The Allocation tab
provides three types of visualization, specific to the TLAB events: Allocation by Class (which
class instances are being allocated), Allocation by Thread (which threads allocate most of the
objects), and Allocation Profile (aggregated stack trace tree of all the events).
A new tab By Top Methods is added to the TLAB Allocations (Thread Local Allocation
Buffers) page in addition to the existing By Threads tab to classify the Item Histograms against
Top Methods. Both tabs now have Alloc in TLABs (%) and Alloc Outside TLABs (%)
columns, which provides estimated allocation size of TLAB as percentage. These updates will
make it easier to view relevant areas of allocation pressure.
Environment
The Environment page provides information about the environment in which the recording
was made. It helps to understand the CPU usage, memory, and operating system that is being
used.
See the Processes page to understand concurrent processes running and the competing CPU
usage of these processes. The application performance will be affected if many processes use
CPU and other system resources.
Check the Event Browser page to see the statistics of all the event types. It helps you to focus
on the bottlenecks and take appropriate action to improve application performance.
You can create Custom Pages using the Event Browser page. Select the required event type
from Event Type Tree and click the Create a new page using the select event type button in
the top right corner of the page. The custom page is listed as a new event page below the
event browser page.
2-10
Chapter 2
Flight Recorder
• Flight Recorder API - Use the [Link] API to extract and format the
information in a recording. For more information, see Flight Recorder API Programmer’s
Guide.
The events in a recording can be used to investigate the following areas:
• General information
– Number of events recorded at each time stamp
– Maximum heap usage
– CPU usage over time, application's CPU usage, and total CPU usage
Watch for CPU usage spiking near 100 percent or the CPU usage is too low or too
long garbage collection pauses.
– GC pause time
– JVM information and system properties set
• Memory
– Memory usage over time
Typically, temporary objects are allocated all the time. When a condition is met, a
Garbage Collection (GC) is triggered and all of the objects no longer used are
removed. Therefore, the heap usage increases steadily until a GC is triggered, then it
drops suddenly. Watch for a steadily increasing heap size over time that could indicate
a memory leak.
– Information about garbage collections, including the time spent doing them
– Memory allocations made
The more temporary objects the application allocates, the more the application must
perform garbage collection. Reviewing memory allocations helps you find the most
allocations and reduce the GC pressure in your application.
– Classes that have the most live set
Watch how each object type increases in size during a flight recording. A specific
object type that increases a lot in size indicates a memory leak; however, a small
variance is normal. Especially, investigate the top growers of non-standard Java
classes.
• Code
– Packages and classes that used the most execution time
Watch where methods are being called from to identify bottlenecks in your application.
– Exceptions thrown
– Methods compiled over time as the application was running
– Number of loaded classes, actual loaded classes and unloaded classes over time
• Threads
– CPU usage and the number of threads over time
– Threads that do most of the code execution
– Objects that are the most waited for due to synchronization
• I/O
– Information about file reads, file writes, socket reads, and socket writes
2-11
Chapter 2
The jcmd Utility
• System
– Information about the CPU, memory and OS of the machine running the application
– Environment variables and any other processes running at the same time as the JVM
• Events
– All of the events in the recording
> jcmd
5485 [Link]/[Link]
2125 MyProgram
2-12
Chapter 2
The jcmd Utility
[Link]
[Link]
[Link]
VM.class_hierarchy
VM.classloader_stats
[Link]
VM.command_line
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
VM.native_memory
VM.print_touched_methods
VM.set_flag
[Link]
[Link]
VM.system_properties
[Link]
[Link]
[Link]
help
Permission: [Link](monitor)
The following sections describe some useful commands and troubleshooting techniques with
the jcmd utility:
2-13
Chapter 2
The jcmd Utility
The following are some of the most useful commands of the jcmd tool:
2-14
Chapter 2
Native Memory Tracking
2-15
Chapter 2
Native Memory Tracking
Because the initial heap size is only 100 MB, only 100 MB will be committed to begin with.
For a 64-bit machine where address space is almost unlimited, there is no problem if a
JVM reserves a lot of memory. The problem arises if more and more memory gets
committed, which may lead to swapping or native out of memory (OOM) situations.
An arena is a chunk of memory allocated using malloc. Memory is freed from these chunks
in bulk, when exiting a scope or leaving an area of code. These chunks can be reused in
other subsystems to hold temporary memory, for example, pre-thread allocations. An
arena malloc policy ensures no memory leakage. So arena is tracked as a whole and not
individual objects. Some initial memory cannot be tracked.
Enabling NMT will result in a 5-10 percent JVM performance drop, and memory usage for
NMT adds 2 machine words to all malloc memory as a malloc header. NMT memory usage
is also tracked by NMT.
- GC (reserved=197237KB, committed=52789KB)
(malloc=9717KB #2877)
(mmap: reserved=187520KB, committed=43072KB)
2-16
Chapter 2
Native Memory Tracking
(malloc=663KB #1914)
(mmap: reserved=72KB, committed=72KB)
• Get detail data: To get a more detailed view of native memory usage, start the JVM with
command line option: -XX:NativeMemoryTracking=detail. This will track exactly what
methods allocate the most memory. Enabling NMT will result in 5-10 percent JVM
performance drop and memory usage for NMT adds 2 words to all malloc memory as
malloc header. NMT memory usage is also tracked by NMT.
The following example shows sample output for virtual memory for tracking level set to
detail, which is shown in addition to the summary output above. One way to get this
sample output is to run: jcmd <pid> VM.native_memory detail.
2-17
Chapter 2
Native Memory Tracking
long, WorkGang*)+0x1a1
[0x00007f5b913d5c78]
HeapRegionManager::commit_regions(unsigned int, unsigned long, WorkGang*)
+0x58
[0x00007f5b913d6c45] HeapRegionManager::expand(unsigned int,
unsigned int, WorkGang*)+0x35
• Get diff from NMT baseline: For both summary and detail level tracking, you can set a
baseline after the application is up and running. Do this by running jcmd <pid>
VM.native_memory baseline after the application warms up. Then, you can runjcmd
<pid> VM.native_memory [Link] or jcmd <pid> VM.native_memory [Link].
The following example shows sample output for the summary difference in native memory
usage since the baseline was set, and this shows us changes in memory usage by
category:
2-18
Chapter 2
Native Memory Tracking
(malloc=49KB #212)
(arena=39KB #68)
- GC (reserved=1209971KB, committed=77267KB)
(malloc=29183KB #872)
(mmap: reserved=1180788KB, committed=48084KB)
The following example is a sample output that shows the detail difference in native
memory usage since the baseline, and is a great way to find specific memory leaks:
[0x00007f5b9175ea8b]
MemBaseline::aggregate_virtual_memory_allocation_sites()+0x11b
[0x00007f5b9175ed68] MemBaseline::baseline_allocation_sites()+0x188
[0x00007f5b9175efff] MemBaseline::baseline(bool)+0x1cf
[0x00007f5b917d19a4] NMTDCmd::execute(DCmdSource, Thread*)+0x2b4
(malloc=1KB type=Native Memory Tracking +1KB
#18 +18)
[0x00007f5b917635b0] MallocAllocationSiteWalker::do_malloc_site(MallocSite
const*)+0x40
[0x00007f5b91740bc8] MallocSiteTable::walk_malloc_site(MallocSiteWalker*)
+0x78
[0x00007f5b9175ec32] MemBaseline::baseline_allocation_sites()+0x52
[0x00007f5b9175efff] MemBaseline::baseline(bool)+0x1cf
(malloc=11KB type=Native Memory Tracking
+10KB #156 +136)
[0x00007f5b91804557] thread_native_entry(Thread*)+0xe7
(mmap: reserved=34868KB, committed=1224KB
+68KB Type=Thread Stack)
2-19
Chapter 2
Native Memory Tracking
[0x00007f5b912e4f13] G1CollectedHeap::initialize()+0x333
[0x00007f5b919da5dd] universe_init()+0xbd
(mmap: reserved=483072KB, committed=7424KB
+1280KB Type=GC)
Category Description
Java Heap The heap where your objects live
Class Class meta data
Thread Memory used by threads, including thread data structure, resource area,
handle area, and so on
Code Generated code
GC Data use by the GC, such as card table, except the remembered sets
GCCardSet Data use by the GC's remembered sets (optional, G1 only)
Compiler Memory tracking used by the compiler when generating code
Internal Memory that does not fit the previous categories, such as the memory
used by the command line parser, JVMTI, properties, and so on
Other Memory not covered by another category
Symbol Memory for symbols
Native Memory Tracking Memory used by NMT
2-20
Chapter 2
JConsole
Category Description
Arena Chunk Memory used by chunks in the arena chunk pool
Logging Memory used by logging
Arguments Memory for arguments
Module Memory used by modules
JConsole
Another useful tool included in the JDK download is the JConsole monitoring tool. This tool is
compliant with JMX. The tool uses the built-in JMX instrumentation in the JVM to provide
information about the performance and resource consumption of running applications.
The JConsole tool can attach to any Java application in order to display useful information
such as thread usage, memory consumption, and details about class loading, runtime
compilation, and the operating system.
This output helps with the high-level diagnosis of problems such as memory leaks, excessive
class loading, and running threads. It can also be useful for tuning and heap sizing.
In addition to monitoring, JConsole can be used to dynamically change several parameters in
the running system. For example, the setting of the -verbose:gc option can be changed so
that the garbage collection trace output can be dynamically enabled or disabled for a running
application.
The following sections describe troubleshooting techniques with the JConsole tool.
• Troubleshoot with the JConsole Tool
• Monitor Local and Remote Applications with JConsole
The following list provides an idea of the data that can be monitored using the JConsole tool.
Each heading corresponds to a tab pane in the tool.
• Overview
This pane displays graphs that shows the heap memory usage, number of threads,
number of classes, and CPU usage over time. This overview allows you to visualize the
activity of several resources at once.
• Memory
– For a selected memory area (heap, non-heap, various memory pools):
* Graph showing memory usage over time
* Current memory size
* Amount of committed memory
* Maximum memory size
2-21
Chapter 2
JConsole
– Garbage collector information, including the number of collections performed, and the
total time spent performing garbage collection
– Graph showing the percentage of heap and non-heap memory currently used
In addition, on this pane you can request garbage collection to be performed.
• Threads
– Graph showing thread usage over time.
– Live threads: Current number of live threads.
– Peak: Highest number of live threads since the JVM started.
– For a selected thread, the name, state, and stack trace, as well as, for a blocked
thread, the synchronizer that the thread is waiting to acquire, and the thread that owns
the lock.
– The Deadlock Detection button sends a request to the target application to perform
deadlock detection and displays each deadlock cycle in a separate tab.
• Classes
– Graph showing the number of loaded classes over time
– Number of classes currently loaded into memory
– Total number of classes loaded into memory since the JVM started, including those
subsequently unloaded
– Total number of classes unloaded from memory since the JVM started
• VM Summary
– General information, such as the JConsole connection data, uptime for the JVM, CPU
time consumed by the JVM, compiler name, total compile time, and so on.
– Thread and class summary information
– Memory and garbage collection information, including number of objects pending
finalization, and so on
– Information about the operating system, including physical characteristics, the amount
of virtual memory for the running process, and swap space
– Information about the JVM itself, such as the arguments and class path
• MBeans
This pane displays a tree structure that shows all platform and application MBeans that are
registered in the connected JMX agent. When you select an MBean in the tree, its
attributes, operations, notifications, and other information are displayed.
– You can invoke operations, if any. For example, the operation dumpHeap for the
HotSpotDiagnostic MBean, which is in the [Link] domain, performs a
heap dump. The input parameter for this operation is the path name of the heap dump
file on the machine where the target VM is running.
– You can set the value of writable attributes. For example, you can set, unset, or
change the value of certain VM flags by invoking the setVMOption operation of the
HotSpotDiagnostic MBean. The flags are indicated by the list of values of the
DiagnosticOptions attribute.
– You can subscribe to notifications, if any, by using the Subscribe and Unsubscribe
buttons.
2-22
Chapter 2
JConsole
2-23
Chapter 2
The jdb Utility
2-24
Chapter 2
The jinfo Utility
See The jdb Command in the Java Development Kit Tool Specifications
2-25
Chapter 2
The jinfo Utility
[Link]=2019-09-17
[Link]=C\:\\Program Files\\Java\\jdk-13
[Link]=\\
[Link]=Zero based
[Link]=\r\n
[Link]=Java Platform API Specification
[Link]=Oracle Corporation
[Link]=
[Link]=HotSpot 64-Bit Tiered Compilers
[Link]=13-ea+29
[Link]=user1
[Link]=;
[Link]=10.0
[Link]=Java(TM) SE Runtime Environment
[Link]=Cp1252
[Link]=Java HotSpot(TM) 64-Bit Server VM
[Link]=https\://[Link]/bugreport/
[Link]=C\:\\Users\\user1\\AppData\\Local\\Temp\\
[Link]=13-ea
[Link]=C\:\\Users\\user1
[Link]=amd64
[Link]=Java Virtual Machine Specification
[Link]=
[Link]=C\:\\Program Files\\Java\\jdk-13\\bin;....
[Link]=mixed mode, sharing
[Link]=Oracle Corporation
[Link]=13-ea+29
[Link]=UnicodeLittle
[Link]=57.0
VM Flags:
The following topic describes the troubleshooting technique with jinfo utility.
If you start the target JVM with the -classpath and -Xbootclasspath arguments, then the
output from jinfo provides the settings for [Link] and [Link]. This
information might be needed when investigating class loader issues.
In addition to getting information from a process, the jhsdb jinfo tool can use a core file as
input. On the Linux operating system, for example, the gcore utility can be used to get a core
file of the process in the preceding example. The core file will be named core.19256 and will
be generated in the working directory of the process. The path to the Java executable file and
the core file must be specified as arguments to the jhsdb jinfo utility, as shown in the
following example.
2-26
Chapter 2
The jmap Utility
Sometimes, the binary name will not be java. This happens when the VM is created using the
JNI invocation API. The jhsdb jinfo tool requires the binary from which the core file was
generated.
JDK Mission Control, Flight Recorder, and jcmd utility can be used for diagnosing problems
with JVM and Java applications. It is suggested to use the latest utility, jcmd instead of the
previous jmap utility for enhanced diagnostics and reduced performance overhead.
If jmap is used with a process or core file without any command-line options, then it prints the
list of shared objects loaded. For more specific information, you can use the options -heap, -
histo, or -clstats. These options are described in the subsections that follow.
If the jmap pid command does not respond because of a hung process, then use the jhsdb
jmap utility to run the Serviceability Agent.
The following sections describe troubleshooting techniques with examples that print memory-
related statistics for a running VM or a core file.
• Heap Configuration and Usage
• Heap Histogram
• Class Loader Statistics
The --heap option is used to get the following Java heap information:
• Information specific to the garbage collection (GC) algorithm, including the name of the GC
algorithm (for example, parallel GC) and algorithm-specific details (such as the number of
threads for parallel GC).
• Heap configuration that might have been specified as command-line options or selected by
the VM based on the machine configuration.
• Heap usage summary: For each generation (area of the heap), the tool prints the total
heap capacity, in-use memory, and available free memory. If a generation is organized as a
collection of spaces (for example, the new generation), then a space-specific memory size
summary is included.
The following example shows output from the jhsdb jmap --heap command.
2-27
Chapter 2
The jmap Utility
Heap Configuration:
MinHeapFreeRatio = 40
MaxHeapFreeRatio = 70
MaxHeapSize = 4253024256 (4056.0MB)
NewSize = 1363144 (1.2999954223632812MB)
MaxNewSize = 2551185408 (2433.0MB)
OldSize = 5452592 (5.1999969482421875MB)
NewRatio = 2
SurvivorRatio = 8
MetaspaceSize = 21807104 (20.796875MB)
CompressedClassSpaceSize = 1073741824 (1024.0MB)
MaxMetaspaceSize = 17592186044415 MB
G1HeapRegionSize = 1048576 (1.0MB)
Heap Usage:
G1 Heap:
regions = 4056
capacity = 4253024256 (4056.0MB)
used = 7340032 (7.0MB)
free = 4245684224 (4049.0MB)
0.17258382642998027% used
G1 Young Generation:
Eden Space:
regions = 7
capacity = 15728640 (15.0MB)
used = 7340032 (7.0MB)
free = 8388608 (8.0MB)
46.666666666666664% used
Survivor Space:
regions = 0
capacity = 0 (0.0MB)
used = 0 (0.0MB)
free = 0 (0.0MB)
0.0% used
G1 Old Generation:
regions = 0
capacity = 250609664 (239.0MB)
used = 0 (0.0MB)
free = 250609664 (239.0MB)
0.0% used
Heap Histogram
The jmap command with the -histo option or the jhsdb jmap --histo command can be used
to get a class-specific histogram of the heap.
The jmap -histo command can print the heap histogram for a running process. Use jhsdb
jmap --histo to print the heap histogram for a core file.
When the jmap -histo command is executed on a running process, the tool prints the number
of objects, memory size in bytes, and fully qualified class name for each class. Internal classes
in the Java HotSpot VM are enclosed within angle brackets. The histogram is useful to
2-28
Chapter 2
The jmap Utility
understand how the heap is used. To get the size of an object, you must divide the total size by
the count of that object type.
The following example shows output from the jmap -histo command when it is executed on a
process with PID number 19256.
2-29
Chapter 2
The jmap Utility
When the jhsdb jmap --histo command is executed on a core file, the tool prints the serial
number, number of instances, bytes, and class name for each class. Internal classes in the
Java HotSpot VM are prefixed with an asterisk (*).
The following example shows output of the jhsdb jmap --histo command when it is executed
on a core file.
2-30
Chapter 2
The jmap Utility
2-31
Chapter 2
The jps Utility
$ jps
16217 MyApplication
16342 jps
The jps utility lists the virtual machines for which the user has access rights. This is
determined by access-control mechanisms specific to the operating system.
In addition to listing the PID, the utility provides options to output the arguments passed to the
application's main method, the complete list of VM arguments, and the full package name of
the application's main class. The jps utility can also list processes on a remote system if the
remote system is running the jstatd daemon.
It supports script execution in both interactive mode and in batch mode. By default, the shell
uses JavaScript, but you can specify any other scripting language for which you supply the
path to the script engine JAR file of .class files.
Thanks to the communication between the Java language and the scripting language, the
jrunscript utility supports an exploratory programming style.
The following sections describe troubleshooting techniques with the jstack and jhsdb jstack
utilities.
• Troubleshoot with the jstack Utility
• Stack Trace from a Core Dump
2-32
Chapter 2
The jstack Utility
• Mixed Stack
A stack trace of all threads can be useful in diagnosing a number of issues, such as deadlocks
or hangs.
The -l option instructs the utility to look for ownable synchronizers in the heap and print
information about [Link]. Without this option, the thread dump includes
information only on monitors.
The output from the jstack pid option is the same as that obtained by pressing Ctrl+\ at the
application console (standard input) or by sending the process a quit signal. See
Control+Break Handler for an example of the output.
Thread dumps can also be obtained programmatically using the [Link]
method, or in the debugger using the debugger option to print all thread stacks (the where
command in the case of the jdb sample debugger).
To get stack traces from a core dump, execute the jhsdb jstack command on a core file, as
shown in the following example.
Mixed Stack
The jhsdb jstack utility can also be used to print a mixed stack; that is, it can print native
stack frames in addition to the Java stack. Native frames are the C/C++ frames associated with
VM code and JNI/native code.
To print a mixed stack, use the --mixed option, as shown in the following example.
No deadlocks found.
----------------- 0 -----------------
----------------- 1 -----------------
"DestroyJavaVM" #18 prio=5 tid=0x000001df4706f000 nid=0x744 waiting on
condition [0x0000000000000000]
[Link]: RUNNABLE
JavaThread state: _thread_blocked
2-33
Chapter 2
The jstack Utility
2-34
Chapter 2
The jstack Utility
[Link]: RUNNABLE
JavaThread state: _thread_blocked
0x00007ffa4529f9f4 ntdll!ZwWaitForAlertByThreadId + 0x14
0x000001df2533d590 ????????
----------------- 15 -----------------
"Sweeper thread" #10 daemon prio=9 tid=0x000001df4706c000 nid=0x1a64 runnable
[0x0000000000000000]
[Link]: RUNNABLE
JavaThread state: _thread_blocked
0x00007ffa4529f9f4 ntdll!ZwWaitForAlertByThreadId + 0x14
----------------- 16 -----------------
"Notification Thread" #11 daemon prio=9 tid=0x000001df47070000 nid=0xddc
runnable [0x0000000000000000]
[Link]: RUNNABLE
JavaThread state: _thread_blocked
0x00007ffa4529f9f4 ntdll!ZwWaitForAlertByThreadId + 0x14
----------------- 17 -----------------
0x00007ffa4529f9f4 ntdll!ZwWaitForAlertByThreadId + 0x14
0x00000f3e40772a94 ????????
----------------- 18 -----------------
"Common-Cleaner" #12 daemon prio=8 tid=0x000001df4706b000 nid=0x2054 in
[Link]() [0x000000a7344fe000]
[Link]: TIMED_WAITING (on object monitor)
JavaThread state: _thread_blocked
0x00007ffa4529c144 ntdll!NtWaitForSingleObject + 0x14
----------------- 19 -----------------
"Java2D Disposer" #13 daemon prio=10 tid=0x000001df4706c800 nid=0x4770 in
[Link]() [0x000000a7345ff000]
[Link]: WAITING (on object monitor)
JavaThread state: _thread_blocked
0x00007ffa4529c144 ntdll!NtWaitForSingleObject + 0x14
----------------- 20 -----------------
"AWT-Shutdown" #14 prio=5 tid=0x000001df4706d800 nid=0x4ed4 in [Link]()
[0x000000a7346fe000]
[Link]: WAITING (on object monitor)
JavaThread state: _thread_blocked
0x00007ffa4529c144 ntdll!NtWaitForSingleObject + 0x14
----------------- 21 -----------------
"AWT-Windows" #15 daemon prio=6 tid=0x000001df4706e800 nid=0x15e8 runnable
[0x000000a7347ff000]
[Link]: RUNNABLE
JavaThread state: _thread_in_native
----------------- 22 -----------------
"AWT-EventQueue-0" #17 prio=6 tid=0x000001df4706a000 nid=0x2f54 waiting on
condition [0x000000a7348fe000]
[Link]: WAITING (parking)
JavaThread state: _thread_blocked
0x00007ffa4529c144 ntdll!NtWaitForSingleObject + 0x14
----------------- 23 -----------------
----------------- 24 -----------------
----------------- 25 -----------------
Frames that are prefixed with an asterisk (*) are Java frames, whereas frames that are not
prefixed with an asterisk are native C/C++ frames.
2-35
Chapter 2
The jstat Utility
The output of the utility can be piped through c++filt to demangle C++ mangled symbol
names. Because the Java HotSpot VM is developed in the C++ language, the jhsdb jstack
utility prints C++ mangled symbol names for the Java HotSpot internal functions.
The c++filt utility is delivered with the native C++ compiler suite gnu on Linux.
Note:
The instrumentation is not accessible on a FAT32 file system.
See The jstat Command in the Java Development Kit Tool Specifications.
The jstat utility uses the virtual machine identifier (VMID) to identify the target process. The
documentation describes the syntax of the VMID, but its only required component is the local
virtual machine identifier (LVMID). The LVMID is typically (but not always) the operating
system's PID for the target JVM process.
The jstat utility provides data similar to the data provided by the vmstat and iostat on Linux
operating systems.
For a graphical representation of the data, you can use the visualgc tool. See The visualgc
Tool.
The following example illustrates the use of the -gcutil option, where the jstat utility
attaches to LVMID number 2834 and takes 7 samples at 250-millisecond intervals.
The output of this example shows you that a young generation collection occurred between the
third and fourth samples. The collection took 0.017 seconds and promoted objects from the
eden space (E) to the old space (O), resulting in an increase of old space utilization from
46.56% to 54.60%.
2-36
Chapter 2
The visualgc Tool
The following example illustrates the use of the -gcnew option where the jstat utility attaches
to LVMID number 2834, takes samples at 250-millisecond intervals, and displays the output. In
addition, it uses the -h3 option to display the column headers after every 3 lines of data.
In addition to showing the repeating header string, this example shows that between the fourth
and fifth samples, a young generation collection occurred, whose duration was 0.02 seconds.
The collection found enough live data that the survivor space 1 utilization (S1U) would have
exceeded the desired survivor size (DSS). As a result, objects were promoted to the old
generation (not visible in this output), and the tenuring threshold (TT) was lowered from 15 to
1.
The following example illustrates the use of the -gcoldcapacity option, where the jstat utility
attaches to LVMID number 21891 and takes 3 samples at 250-millisecond intervals. The -t
option is used to generate a time stamp for each sample in the first column.
The Timestamp column reports the elapsed time in seconds since the start of the target JVM.
In addition, the -gcoldcapacity output shows the old generation capacity (OGC) and the old
space capacity (OC) increasing as the heap expands to meet the allocation or promotion
demands. The OGC has grown from 11696 KB to 13820 KB after the 81st full generation
capacity (FGC). The maximum capacity of the generation (and space) is 60544 KB (OGCMX),
so it still has room to expand.
The visualgc tool is related to the jstat tool. See The jstat Utility. The visualgc tool provides
a graphical view of the garbage collection (GC) system. As with jstat, it uses the built-in
instrumentation of the Java HotSpot VM.
The visualgc tool is not included in the JDK release, but is available as a separate download
from the jvmstat technology page.
2-37
Chapter 2
Control+Break Handler
Control+Break Handler
On Linux operating systems, the combination of pressing the Control key and the backslash (\)
key at the application console (standard input) causes the Java HotSpot VM to print a thread
dump to the application's standard output. On Windows, the equivalent key sequence is the
Control and Break keys. The general term for these key combinations is the Control+Break
handler.
On Linux operating systems, a thread dump is printed if the Java process receives a quit
signal. Therefore, the kill -QUIT pid command causes the process with the ID pid to print a
thread dump to standard output.
The following sections describe the data traced by the Control+Break handler:
• Thread Dump
• Thread States for a Thread Dump
• Detect Deadlocks
• Heap Summary
2-38
Chapter 2
Control+Break Handler
Thread Dump
The thread dump consists of the thread stack, including the thread state, for all Java threads in
the virtual machine.
The thread dump does not terminate the application: it continues after the thread information is
printed.
The following example illustrates a thread dump.
2-39
Chapter 2
Control+Break Handler
at [Link](Native Method)
- waiting on <0xf4000a40> (a [Link]$Lock)
at [Link]([Link])
at [Link]$[Link]([Link])
- locked <0xf4000a40> (a [Link]$Lock)
The output consists of a number of thread entries separated by an empty line. The Java
Threads (threads that are capable of executing Java language code) are printed first, and
these are followed by information about VM internal threads. Each thread entry consists of a
header line followed by the thread stack trace.
The header line contains the following information about the thread:
• Thread name.
• Indication if the thread is a daemon thread.
• Thread priority (prio).
• Thread ID (tid), which is the address of a thread structure in memory.
• ID of the native thread (nid).
• Thread state, which indicates what the thread was doing at the time of the thread dump.
See Table 2-2 for more details.
• Address range, which gives an estimate of the valid stack region for the thread.
Detect Deadlocks
The Control+Break handler can be used to detect deadlocks in threads.
In addition to the thread stacks, the Control+Break handler executes a deadlock detection
algorithm. If any deadlocks are detected, then the Control+Break handler, as shown in the
2-40
Chapter 2
Control+Break Handler
following example, prints additional information after the thread dump about each deadlocked
thread.
Found one Java-level deadlock:
=============================
"Thread2":
waiting to lock monitor 0x000af330 (object 0xf819a938, a [Link]),
which is held by "Thread1"
"Thread1":
waiting to lock monitor 0x000af398 (object 0xf819a970, a [Link]),
which is held by "Thread2"
Found 1 deadlock.
If the JVM flag -XX:+PrintConcurrentLocks is set, then the Control+Break handler will also
print the list of concurrent locks owned by each thread.
Heap Summary
The Control+Break handler can be used to print a heap summary.
The following example shows the different generations (areas of the heap), with the size, the
amount used, and the address range. The address range is especially useful if you are also
examining the process with tools such as pmap.
Heap
def new generation total 1152K, used 435K [0x22960000, 0x22a90000,
0x22e40000
)
eden space 1088K, 40% used [0x22960000, 0x229ccd40, 0x22a70000)
from space 64K, 0% used [0x22a70000, 0x22a70000, 0x22a80000)
to space 64K, 0% used [0x22a80000, 0x22a80000, 0x22a90000)
tenured generation total 13728K, used 6971K [0x22e40000, 0x23ba8000,
0x269600
00)
the space 13728K, 50% used [0x22e40000, 0x2350ecb0, 0x2350ee00,
0x23ba8000)
compacting perm gen total 12288K, used 1417K [0x26960000, 0x27560000,
0x2a9600
00)
the space 12288K, 11% used [0x26960000, 0x26ac24f8, 0x26ac2600,
0x27560000)
ro space 8192K, 62% used [0x2a960000, 0x2ae5ba98, 0x2ae5bc00, 0x2b160000)
rw space 12288K, 52% used [0x2b160000, 0x2b79e410, 0x2b79e600,
0x2bd60000)
2-41
Chapter 2
Native Operating System Tools
If the JVM flag -XX:+PrintClassHistogram is set, then the Control+Break handler will
produce a heap histogram.
Tool Description
dumpchk Command-line utility to verify that a memory dump file was created
correctly. This tool is included in the Debugging Tools for Windows
download available from the Microsoft website. See Collect Crash
Dumps on Windows.
msdev debugger Command-line utility that can be used to launch Visual C++ and the
Win32 debugger
userdump The User Mode Process Dumper is included in the OEM Support Tools
download available from the Microsoft website. See Collect Crash
Dumps on Windows.
windbg Windows debugger can be used to debug Windows applications or crash
dumps. This tool is included in the Debugging Tools for Windows
download available from the Microsoft website. See Collect Crash
Dumps on Windows.
/Md and /Mdd compiler Compiler options that automatically include extra support for tracking
options memory allocations
Table 2-4 describes some troubleshooting tools introduced or improved in the Linux operating
system version 10.
2-42
Chapter 2
Native Operating System Tools
Tool Description
c++filt Demangle C++ mangled symbol names. This utility is delivered with the
native C++ compiler suite: gcc on Linux.
gdb GNU debugger
libnjamd Memory allocation tracking
lsstack Print thread stack
Not all distributions provide this tool by default; therefore, you might have
to download it from SourceForge.
ltrace Library call tracer
Not all distributions provide this tool by default; therefore, you might have
to download it from SourceForge.
mtrace and muntrace GNU malloc tracer
/proc filesystem Virtual filesystem that contains information about processes and other
system information
strace System call tracer
top Display most CPU-intensive processes.
vmstat Report information about processes, memory, paging, block I/O, traps,
and CPU activity.
These providers deliver probes that can be used to monitor the internal state and activities of
the VM, as well as the Java application that is running.
The JVM probe providers can be categorized as follows:
• VM lifecycle: VM initialization begin and end, and VM shutdown
• Thread lifecycle: thread start and stop, thread name, thread ID, and so on
• Class-loading: Java class loading and unloading
• Garbage collection: Start and stop of garbage collection, systemwide or by memory pool
• Method compilation: Method compilation begin and end, and method loading and
unloading
• Monitor probes: Wait events, notification events, contended monitor entry and exit
• Application tracking: Method entry and return, allocation of a Java object
In order to call from native code to Java code, the native code must make a call through the
JNI interface. The hotspot_jni provider manages DTrace probes at the entry point and return
point for each of the methods that the JNI interface provides for invoking Java code and
examining the state of the VM.
At probe points, you can print the stack trace of the current thread using the ustack built-in
function. This function prints Java method names in addition to C/C++ native function names.
2-43
Chapter 2
Custom Diagnostic Tools
The following example is a simple D script that prints a full stack trace whenever a thread calls
the read system call.
#!/usr/sbin/dtrace -s
syscall::read:entry
/pid == $1 && tid == 1/ {
ustack(50, 0x2000);
}
The script in the previous example is stored in a file named read.d and is run by specifying the
PID of the Java process that is traced as shown in the following example.
read.d pid
If your Java application generated a lot of I/O or had some unexpected latency, then the
DTrace tool and its ustack() action can help you to diagnose the problem.
2-44
Chapter 2
Custom Diagnostic Tools
2-45
Chapter 2
Postmortem Diagnostic Tools
debugger-like application (for example, IDE, debugger, tracer, or monitoring tool) is the
client. See the module [Link].
• The Java Debug Wire Protocol (JDWP) defines the format of information and requests
transferred between the process being debugged and the debugger front end, which
implements the JDI.
The jdb utility is included in the JDK as an example command-line debugger. The jdb utility
uses the JDI to launch or connect to the target VM. See The jdb Utility.
In addition to traditional debugger-type tools, the JDI can also be used to develop tools that
help in postmortem diagnostics and scenarios where the tool needs to attach to a process in a
noncooperative manner (for example, a hung process).
2-46
Chapter 2
Hung Processes Tools
Monitoring Tools
Tools and options for monitoring running applications and detecting problems are available in
the JDK and in the operating system.
2-47
Chapter 2
Other Tools, Options, Variables, and Properties
The tools listed in the Table 2-7 are designed for monitoring applications that are running.
JDK Mission Control, Flight Recorder and the jcmd utility can be used to diagnose problems
with JVM and Java applications. It is suggested to use the latest utility, jcmd, instead of the
previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance
overhead.
2-48
Chapter 2
The jstatd Daemon
Note:
The instrumentation is not accessible on FAT32 file system.
2-49
3
Troubleshoot Memory Leaks
This chapter provides some suggestions for diagnosing problems involving possible memory
leaks.
If your application's execution time becomes longer, or if the operating system seems to be
performing slower, this could be an indication of a memory leak. In other words, virtual memory
is being allocated but is not being returned when it is no longer needed. Eventually the
application or the system runs out of memory, and the application terminates abnormally.
This chapter contains the following sections:
• The [Link] Error
• Detecting a Memory Leak
• Diagnosing Java Memory Leaks
• Diagnosing Native Memory Leaks
• Monitoring the Objects Pending Finalization
• Troubleshooting a Crash Instead of a [Link] error
3-1
Chapter 3
The [Link] Error
Note:
The APIs that are called by an application could also unintentionally be holding
object references.
One other potential source of this error arises with applications that make excessive use of
finalizers. If a class has a finalize method, then objects of that type do not have their space
reclaimed at garbage collection time. Instead, after garbage collection, the objects are queued
for finalization, which occurs at a later time. In the Oracle implementations of the Java
Runtime, finalizers are executed by a daemon thread that services the finalization queue. If
the thread cannot keep up with the finalization queue, then the Java heap could fill up, and
this kind of [Link] error would be thrown. One scenario that can cause
this situation is when an application creates high-priority threads that cause the finalization
queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing
that queue.
Action: Try increasing the Java heap size. See Monitoring the Objects Pending Finalization to
learn more about how to monitor objects for which finalization is pending. See Finalization and
Weak, Soft, and Phantom References in Java Platform, Standard Edition HotSpot Virtual
Machine Garbage Collection Tuning Guide for information about detecting and migrating from
finalization.
Action: Increase the heap size. The [Link] error for GC Overhead
limit exceeded can be turned off using the command-line flag -XX:-UseGCOverheadLimit.
Action: Ensure that your application (or APIs used by that application) allocates an array with
a size less than the VM implementation limit
Action: If MaxMetaSpaceSize has been specified on the command-line, increase its value.
Metaspace is allocated from the same address space as the Java heap. Reducing the size of
the Java heap will make more space available for Metaspace. This trade-off is only useful if
3-2
Chapter 3
The [Link] Error
there is an excess of free space in the Java heap. See the following action for the Out of
swap space detail message.
Detail Message: request size bytes for reason. Out of swap space?
Cause: The detail message request size bytes for reason. Out of swap space? appears to
be a [Link] error. However, Java reports this apparent error when an
allocation from the native heap failed and the native heap might be close to exhaustion. The
message indicates the size (in bytes) of the request that failed and the reason for the memory
request. Usually the reason is the name of a source module reporting the allocation failure,
although sometimes it indicates the actual reason.
Action: When this error is thrown, the Java VM (JVM) invokes the fatal error handling
mechanism: it generates a fatal error log file, which contains useful information about the
thread, process, and system at the time of the crash. In the case of native heap exhaustion,
the heap memory and memory map information in the log can be useful. See Fatal Error Log.
You might need to use troubleshooting utilities for the operating system to diagnose the issue
further. See Native Operating System Tools.
Note:
There are bounds on the acceptable size of CompressedClassSpaceSize. For
example -XX:CompressedClassSpaceSize=4g, exceeds acceptable bounds and will
result in a message such as
Note:
There is more than one kind of class metadata: –klass metadata, and other
metadata. Only klass metadata is stored in the space bounded by
CompressedClassSpaceSize. Other metadata is stored in Metaspace.
3-3
Chapter 3
Detecting a Memory Leak
Action: If this type of [Link] error is thrown, you might need to use
native utilities of the operating system to diagnose the issue further. See Native Operating
System Tools.
For detecting memory leaks, it is important to monitor the live set of the application that is, the
amount of Java heap space or Metaspace being used after a full garbage collection. If the live
set increases over time after the application has reached a stable state and is under a stable
load, that could be a strong indication of a memory leak. The live set and memory usage of an
application can be monitored by using JConsole and JDK Mission Control. The memory
usage information can also be extracted from garbage collection logs.
Note that if the detail message of the error suggests the exhaustion of the native heap, the
application could be encountering a native memory leak. To confirm native memory leaks, use
native tools such as pmap or PerfMon, and compare their periodically-collected output to
determine the newly-allocated or growing memory sections of the process.
JConsole
JConsole is a great tool for monitoring resources of Java applications. Among other things, it is
helpful in monitoring the usage of various memory pools of an application, including
generations of Java heap, Metaspace, Compressed Class Space, and CodeHeap.
In the following screenshots, for an example program, the JConsole shows the usage of Heap
Memory and Old Generation steadily increasing over a period of time. This steady growth in
memory usage even after several full garbage collections indicates a memory leak.
3-4
Chapter 3
Detecting a Memory Leak
3-5
Chapter 3
Detecting a Memory Leak
Start JMC and start a Time fixed recording (profiling recording) for an hour. Before starting a
flight recording, make sure that the option Object Types + Allocation Stack Traces + Path to
GC Root is selected from the Memory Leak Detection setting.
Once the recording is complete, the recording file (.jfr) opens in JMC. Look at the
Automated Analysis Results page. To detect a memory leak focus on the Live Objects
section of the page. Here is an example of a recording, which shows a heap size issue:
3-6
Chapter 3
Detecting a Memory Leak
You can observe that in the Heap Live Set Trend section, the live set on the heap seems to
increase rapidly and the analysis of the reference tree detected a leak candidate.
For further analysis, open the Java Applications page and then click the Memory page. Here
is a sample figure of a recording, which shows memory leak issue.
You can observe from the graph that the memory usage has increased steadily, which
indicates a memory leak issue.
3-7
Chapter 3
Diagnosing Java Memory Leaks
GC logs can be collected using the –Xlog command-line Java option. An example is given
below:
-Xlog:gc*,gc+phases=debug:[Link]
This will log messages tagged with at least gc using info level, and messages tagged with
exactly gc and phases tags using debug level to a file called [Link].
In this example, the Java heap is sized at 48M, and the Full GC was not able to reclaim any
space. It is clear that the Old generation is completely full, and the Full GC could not help
much. This suggests that either the heap is sized smaller than the application’s heap
requirements, or there is a memory leak.
Diagnostic Data
This section looks at the diagnostic data you can use to troubleshoot memory leaks.
Heap Histograms
You can try to quickly narrow down a memory leak by examining the heap histogram. You can
get a heap histogram in several ways:
3-8
Chapter 3
Diagnosing Java Memory Leaks
The output shows the total size and instance count for each class type in the heap. If a
sequence of histograms is obtained (for example, every two minutes), then you might be
able to see a trend that can lead to further analysis.
• You can use the jhsdb jmap utility to get a heap histogram from a core file, as shown in
the following example.
3-9
Chapter 3
Diagnosing Java Memory Leaks
The above example shows that the [Link] error was caused by the
number of byte arrays (2108 instances in the heap). Without further analysis it is not clear
where the byte arrays are allocated. However, the information is still useful.
Heap Dumps
Heap dumps are the most important data to troubleshoot memory leaks. Heap dumps can be
collected using jcmd, jmap, JConsole tools, and the -XX:+HeapDumpOnOutOfMemoryError Java
option
• You can use the GC.heap_dump command with the jcmd utility to create a heap dump as
shown below:
• The MBean browser in JConsole makes the HotSpotDiagnostic MBean available, and
that can be used to create heap dumps for the attached Java process.
• You can use the -XX:+HeapDumpOnOutOfMemoryError Java option to dump the Java heap
of a process when it fails with a [Link] error.
3-10
Chapter 3
Diagnosing Java Memory Leaks
Heap Statistics can also be enabled by manually editing the .jfc file, and setting heap-
statistics-enabled to true.
<event path="vm/gc/detailed/object_count">
<setting name="enabled" control="heap-statistics-enabled">true</setting>
<setting name="period">everyChunk</setting>
</event>
The flight recordings can then be created using any of the following ways:
• Java Flight Recorder options
-
XX:StartFlightRecording=delay=20s,duration=60s,name=MyRecording,filename=my
[Link],settings=profile
• JMC
3-11
Chapter 3
Diagnosing Java Memory Leaks
3-12
Chapter 3
Diagnosing Java Memory Leaks
Analysis Tools
This section explores the analysis tools you can use to diagnose memory leaks, including
those that can analyze diagnostic data described above.
You can observe that most of the live objects being tracked are held by Leak$DemoThread,
which in turn holds a leaked char[] class. For further analysis, see the Old Object Sample
event in the Results tab that contains sampling of the objects that have survived. This event
contains the time of allocation, the allocation stack trace, and the path back to the GC root.
When a potentially leaking class is identified, look at the TLAB Allocations page in the JVM
Internals page for some samples of where objects were allocated. Here is a sample recording,
showing TLAB allocations.
3-13
Chapter 3
Diagnosing Java Memory Leaks
Check the class samples being allocated. If the leak is slow, there may be a few allocations of
this object and may be no samples. Also, it may be that only a specific allocation site is leading
to a leak. You can make required changes to the code to fix the leaking class.
$ java -XX:StartFlightRecording
When the JVM runs out of memory and exits due to a [Link] error, a
recording with the prefix hs_oom_pid is often, but not always, written to the directory in which
the JVM was started. An alternative way to get a recording is to dump it before the application
runs out of memory using the jcmd tool, as shown in the following example:
When you have a recording, use the jfr tool located in the java-home/bin directory to print
Old Object Sample events that contain information about potential memory leaks. The
following example shows the command and an example of the output from a recording for an
application with the pid 16276:
3-14
Chapter 3
Diagnosing Java Memory Leaks
[Link] {
startTime = [Link].192
duration = 5.317 s
allocationTime = [Link].213
objectAge = 74.0 s
lastKnownHeapUsage = 63.9 MB
object = [
[Link]$Node
[15052855] : [Link]$Node[33554432]
table : [Link] Size: 15000000
map : [Link]
users : [Link] Class Name: Application
]
arrayElements = N/A
root = {
description = "Thread Name: main"
system = "Threads"
type = "Stack Variable"
}
eventThread = "main" (javaThreadId = 1)
}
...
[Link] {
startTime = [Link].192
duration = 5.317 s
allocationTime = [Link].266
objectAge = 74.0 s
lastKnownHeapUsage = 84.4 MB
object = [
[Link]$Node
[8776975] : [Link]$Node[33554432]
table : [Link] Size: 15000000
map : [Link]
users : [Link] Class Name: Application
]
arrayElements = N/A
root = {
description = "Thread Name: main"
system = "Threads"
type = "Stack Variable"
}
eventThread = "main" (javaThreadId = 1)
}
...
[Link] {
startTime = [Link].192
duration = 5.317 s
allocationTime = [Link].540
objectAge = 73.7 s
lastKnownHeapUsage = 121.7 MB
object = [
3-15
Chapter 3
Diagnosing Java Memory Leaks
[Link]$Node
[393162] : [Link]$Node[33554432]
table : [Link] Size: 15000000
map : [Link]
users : [Link] Class Name: Application
]
arrayElements = N/A
root = {
description = "Thread Name: main"
system = "Threads"
type = "Stack Variable"
}
eventThread = "main" (javaThreadId = 1)
}
...
To identify a possible memory leak, review the following elements in the recording:
• First, notice that the lastKnownHeapUsage element in the Old Object Sample events is
increasing over time, from 63.9 MB in the first event in the example to 121.7 MB in the last
event. This increase is an indication that there is a memory leak. Most applications allocate
objects during startup and then allocate temporary objects that are periodically garbage
collected. Objects that are not garbage collected, for whatever reason, accumulate over
time and increase the value of lastKnownHeapUsage.
• Next, look at the allocationTime element to see when the object was allocated. Objects
that are allocated during startup are typically not memory leaks, neither are objects
allocated close to when the dump was taken. The objectAge element shows how long the
object has been alive. The startTime and duration elements are not related to when the
memory leak occurred, but when the OldObject event was emitted and how long it took to
gather data for it. This information can be ignored.
• Then look at the object element to see the memory leak candidate; in this example, an
object of type [Link]$Node. It is held by the table field in the
[Link] class, which is held by [Link], which in turn is held
by the users field of the Application class.
• The root element contains information about the GC root. In this example, the
Application class is held by a stack variable in the main thread. The eventThread
element provides information about the thread that allocated the object.
If the application is started with the -XX:StartFlightRecording:settings=profile option,
then the recording also contains the stack trace from where the object was allocated, as shown
in the following example:
stackTrace = [
[Link](int, Object, Object, HashMap$Node) line: 1885
[Link](int, Object, Object, boolean, boolean) line: 631
[Link](Object, Object) line: 612
[Link](Object) line: 220
[Link](String, String) line: 53
[Link](String, String) line: 48
[Link](String, String) line: 44
[Link](String[]) line: 30
]
3-16
Chapter 3
Diagnosing Native Memory Leaks
In this example we can see that the object was put in the HashSet when the
storeUser(String, String) method was called. This suggests that the cause of the memory
leak might be objects that were not removed from the HashSet when the user logged out.
NetBeans Profiler
The NetBeans Profiler can locate memory leaks very quickly. Commercial memory leak
debugging tools can take a long time to locate a leak in a large application. The NetBeans
Profiler, however, uses the pattern of memory allocations and reclamations that such objects
typically demonstrate. This process includes also the lack of memory reclamations. The profiler
can check where these objects were allocated, which often is sufficient to identify the root
cause of the leak.
See Introduction to Profiling Java Applications in NetBeans IDE.
3-17
Chapter 3
Diagnosing Native Memory Leaks
Native memory leaks can result from native allocations performed either internally by the JVM,
or from outside the JVM. The following two sections discuss in detail how both of these
memory leaks can be diagnosed.
-XX:NativeMemoryTracking=summary
-XX:NativeMemoryTracking=detail
• The jcmd tool can then be used to attach to the NMT-enabled process, and obtain its
native memory usage details. It is also possible to collect a baseline of memory usage and
then collect the difference in usage against that baseline.
Note:
Enabling NMT can result in a performance drop of around 5 to 10 percent. Therefore,
it should be enabled in production systems cautiously. Additionally, the native
memory used by NMT is tracked by the tool itself.
In the following example, the JConsole screenshot shows that the usage of ‘Compressed
Class Space’ is growing at a constant rate over time.
3-18
Chapter 3
Diagnosing Native Memory Leaks
To diagnose this usage growth, the Java process can be tracked using the NMT. Collecting a
baseline and a [Link] output shows that the class space usage is increasing
dramatically due to the corresponding increase in the number of loaded classes.
3-19
Chapter 3
Diagnosing Native Memory Leaks
3-20
Chapter 3
Diagnosing Native Memory Leaks
Valgrind
Valgrind can be used to diagnose native memory leaks on Linux. To monitor a Java process
using Valgrind, it can be launched as follows:
A suppression file can be supplied to valgrind with --log-file option in order for it to not
consider the JVM internal allocations (such as the Java heap allocation) as potential memory
leaks, otherwise it becomes very difficult to parse through the verbose output and manually
look for relevant leak reports.
The following are the contents of a sample suppression file:
{
name
Memcheck:Leak
fun:*alloc
...
obj:/opt/java/jdk16/jre/lib/amd64/server/[Link]
...
}
With the above command, and with suppressions in place, Valgrind writes the identified leaks
in the specified log file. An example is shown below:
==5200== 88 bytes in 1 blocks are still reachable in loss record 461 of 18,861
==5200== at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-
[Link])
==5200== by 0x7DCB156: Java_java_util_zip_Deflater_init
(in /opt/jdk/ /jre/lib/amd64/[Link])
==5200== by 0x80F54FC: ???
==5200== by 0x8105F87: ???
==5200== by 0xFFFFFFFE: ???
==5200== by 0xEC67F74F: ???
==5200== by 0xC241B03F: ???
==5200== by 0xEC67D767: ???
==5200== by 0x413F96F: ???
==5200== by 0x8101E7B: ???
==5200==
==5200== 88 bytes in 1 blocks are still reachable in loss record 462 of 18,861
==5200== at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-
[Link])
==5200== by 0x7DCB156: Java_java_util_zip_Deflater_init
(in /opt/jdk/jre/lib/amd64/[Link])
==5200== by 0x80F54FC: ???
==5200== by 0x8105F87: ???
==5200== by 0xFFFFFFFE: ???
==5200== by 0xEC67FF3F: ???
==5200== by 0xC241B03F: ???
==5200== by 0xEC630EB7: ???
==5200== by 0x413F96F: ???
3-21
Chapter 3
Diagnosing Native Memory Leaks
In the above output, Valgrind correctly reports that there are allocations leaking from
Java_java_util_zip_Deflater_init native method.
Note:
Using Valgrind may have a negative impact on the performance of the monitored
application.
From the previous pmap output, we can see that the memory block at 00007f6d690a3000 is
growing between the two memory snapshots of the process. Using a core file collected from
the process, we can examine the contents of this memory block.
The above shows that there is a repeating string, "Alert: JNI Memory Leak", present in that
memory block. Searching in the source code for the string or contents found in the relevant
memory block can lead us to the culprit in the code. Here is the code used for this example,
where these allocations are performed in JNI code and are not being released.
3-22
Chapter 3
Diagnosing Native Memory Leaks
Hence, the pmap tool and core files can help in getting to the root of native memory leaks
caused by allocations performed outside of the JVM.
#include <stdlib.h>
#define malloc(n) debug_malloc(n, __FILE__, __LINE__)
#define free(p) debug_free(p, __FILE__, __LINE__)
Then, you can use the functions in the following example to watch for leaks.
The JNI library would then need to periodically (or at shutdown) check the value of the
total_allocated variable to verify that it made sense. The preceding code could also be
expanded to save in a linked list the allocations that remained, and report where the leaked
memory was allocated. This is a localized and portable way to track memory allocations in a
single set of sources. You would need to ensure that debug_free() was called only with the
3-23
Chapter 3
Monitoring the Objects Pending Finalization
pointer that came from debug_malloc(), and you would also need to create similar functions
for realloc(), calloc(), strdup(), and so forth, if they were used.
A more global way to look for native heap memory leaks involves interposition of the library
calls for the entire process.
3-24
4
Troubleshoot Performance Issues Using Flight
Recorder
This chapter describes how to identify performance issues with a Java application and debug
these issues using flight recordings.
To learn more about creating a recording with Flight Recorder in Java Mission Control (JMC),
see Start a Flight Recording.
The data provided by Flight Recorder helps you investigate performance issues. No other tool
gives as much profiling data without skewing the results with its own performance overhead.
This chapter provides information about performance issues that you can identify and debug
using data from Flight Recorder.
This chapter contains the following sections:
• Flight Recorder Overhead
• Find Bottlenecks
• Garbage Collection Performance
• Synchronization Performance
• I/O Performance
• Code Execution Performance
Note:
For performance profiling use cases, heap statistics may not be necessary.
4-1
Chapter 4
Find Bottlenecks
Find Bottlenecks
Different applications have different bottlenecks. Waiting for I/O or networking, synchronization
between threads, CPU usage or garbage collection times can cause bottlenecks in an
application. It is possible that an application has more than one bottleneck.
Topics:
• Find Bottlenecks
• Use the jfr Tool to Find Bottlenecks
Find Bottlenecks
Different applications have different bottlenecks. For some applications, a bottleneck may be
waiting for I/O or networking, it may be synchronization between threads, or it may be actual
CPU usage. For others, a bottleneck may be garbage collection times. It is possible that an
application has more than one bottleneck.
One way to find the application bottlenecks is to look at the following events in your flight
recording. Make sure that all of these events are enabled in the recording template that you
are using:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
The selected Java Application events all have the important property that they are all thread-
stalling events. Thread stalling indicates that the thread was not running your application
during the event, and they are all duration events. The duration event measures the duration
the application was not running.
Use the jfr tool to print the events that were recorded and look for the following information:
• [Link] events show how much time a thread spends waiting for a monitor.
• [Link] and [Link] events show when a thread is sleeping or parked.
• Read and write events show how much time is spent in I/O.
If your Java application's important threads spend a lot of time being blocked, then that means
that a critical section of the application is single threaded, which is a bottleneck. If the Java
application spends a lot of time waiting for sockets, then the main bottleneck may be in the
4-2
Chapter 4
Find Bottlenecks
network or with the other machines that the application communicates with. If your Java
application's important threads are spending a lot of time without generating any application
events, then the bottleneck in the application is the time spent executing code or the CPU
itself. Each of these bottlenecks can be further investigated within the flight recording.
Note:
For most Java Application event types, only events longer than 20 ms are recorded.
(This threshold can be modified when starting the flight recording.) To summarize, the
areas may not have recorded events because the application is doing a lot of short
tasks, such as writing to a file (a small part at a time) or spending time in
synchronization for very short amounts of time.
• [Link] events show how much time a thread spends waiting for a monitor.
• [Link] and [Link] events show when a thread is sleeping or parked.
• Read and write events show how much time is spent in I/O.
4-3
Chapter 4
Garbage Collection Performance
If your Java application's important threads spend a lot of time being blocked, then that means
that a critical section of the application is single threaded, which is a bottleneck. If the Java
application spends a lot of time waiting for sockets, then the main bottleneck may be in the
network or with the other machines that the application communicates with. If your Java
application's important threads are spending a lot of time without generating any application
events, then the bottleneck in the application is the time spent executing code or the CPU
itself. Each of these bottlenecks can be further investigated within the flight recording.
Note:
For most Java Application event types, only events longer than 20 ms are recorded.
(This threshold can be modified when starting the flight recording.) To summarize, the
areas may not have recorded events because the application is doing a lot of short
tasks, such as writing to a file (a small part at a time) or spending time in
synchronization for very short amounts of time.
Topics:
• Use JDK Mission Control to Debug Garbage Collection Issues
• Use the jfr Tool to Debug Garbage Collection Issues
4-4
Chapter 4
Garbage Collection Performance
You can observe from the figure that there is a Full GC event. This is indicative of the fact that
application needs more memory than what you have allocated.
For further analysis, open the Garbage Collections page under the JVM Internals page to
investigate the overall performance impact of the GC. Here is a sample figure of a recording,
which shows a graph with GC pauses.
From the graph look at the Sum of Pauses from the recording. The Sum of Pauses is the
total amount of time that the application was paused during a GC. Many GCs do most of their
work in the background. In those cases, the length of the GC does not matter and what matters
is how long the application actually had to stop. Therefore, the Sum of Pauses is a good
measure for the GC effect.
The main performance problems with garbage collections are usually either that individual GCs
take too long, or that too much time is spent in paused GCs (total GC pauses).
4-5
Chapter 4
Garbage Collection Performance
When an individual GC takes too long, you may need to change the GC strategy. Different GCs
have different trade-offs when it comes to pause times verses throughput performance. See
Behavior-Based Tuning in Java Platform, Standard Edition HotSpot Virtual Machine Garbage
Collection Tuning Guide.
In addition, you may also need to fix your application so that it makes less use of finalizers or
semireferences. See Monitoring the Objects Pending Finalization and Finalization and Weak,
Soft, and Phantom References in Java Platform, Standard Edition HotSpot Virtual Machine
Garbage Collection Tuning Guide for information about detecting and migrating from
finalization.
If the application spends too much time paused, you can look into different ways to overcome
this. One way is to increase the Java heap size. Look at the GC Configuration page to
estimate the heap size used by the application, and change the initial heap size and maximum
heap size to a higher value. The bigger the heap, the longer time it is between GCs. Watch out
for any memory leaks in the Java application, because that may cause more frequent GCs until
an OutOfMemoryError is thrown. For more information, see The jfr tool. Another way to reduce
the GC cycles is to allocate fewer temporary objects. In the TLAB Allocations page, look at
how much memory is allocated over the course of the recording. Small objects are allocated in
a Thread Local Area Buffer (TLAB). TLAB is a small memory area where new objects are
allocated. Once a TLAB is full, the thread gets a new one. Larger objects are allocated outside
a TLAB. Often, the majority of allocations happen inside a TLAB. Lastly, to reduce the need of
GCs, decrease the allocation rate. Select the TLAB Allocations page and then look at the
allocation sites that have the most memory pressure. You can either view it per class or thread
to see which one consumes the most allocation.
Some other settings may also increase GC performance of the Java application. See Garbage
Collection Tuning Guide in Java Platform, Standard Edition HotSpot Virtual Machine Garbage
Collection Tuning Guide for more information about GC performance.
4-6
Chapter 4
Synchronization Performance
Using the information from the [Link] events, you can calculate the average sum
of pauses for each GC, the maximum sum of pauses, and the total pause time. The sum of
pauses is the total amount of time that the application was paused during a GC. Many GCs do
most of their work in the background. In those cases, the length of the GC does not matter and
what matters is how long the application actually had to stop. Therefore, the sum of pauses is
a good measure for the GC effect.
The main performance problems with garbage collections are usually either that individual GCs
take too long, or that too much time is spent in paused GCs (total GC pauses).
When an individual GC takes too long, you may need to change the GC strategy. Different GCs
have different trade-offs when it comes to pause times versus throughput performance. See
Behavior-Based Tuning in Java Platform, Standard Edition HotSpot Virtual Machine Garbage
Collection Tuning Guide.
In addition, you may also need to fix your application so that it makes less use of finalizers or
semireferences. See Monitoring the Objects Pending Finalization and Finalization and Weak,
Soft, and Phantom References in Java Platform, Standard Edition HotSpot Virtual Machine
Garbage Collection Tuning Guide for information about detecting and migrating from
finalization.
When the application spends too much time paused, there are different ways to work around
that:
• Increase the Java heap size. The bigger the Java heap, the longer time it is between GCs.
Watch out for any memory leaks in the Java application, because that may cause more
and more frequent GCs until an OutOfMemoryError is thrown. For more information, see
The jfr tool.
• To reduce the number of GCs, allocate fewer temporary objects. Small objects are
allocated in a Thread Local Area Buffer (TLAB). TLAB is a small memory area where new
objects are allocated. Once a TLAB is full, the thread gets a new one. Larger objects are
allocated outside a TLAB. Often, the majority of allocations happen inside a TLAB. The
[Link] and [Link] events provide
information about the allocation of temporary objects.
• To reduce the need of GCs, decrease the allocation rate. The
[Link] event provides information about the allocations per
thread.
Some other settings may also increase GC performance of the Java application. See Garbage-
First Garbage Collection in Java Platform, Standard Edition HotSpot Virtual Machine Garbage
Collection Tuning Guide for more information about GC performance.
Synchronization Performance
Java applications encounter synchronization issues when the application threads spend a lot of
time waiting to enter a monitor.
Topics:
• Synchronization Performance
• Use [Link] Events to Debug Synchronization Issues
4-7
Chapter 4
Synchronization Performance
Synchronization Performance
To debug Java Application synchronization issues, which is where the application threads
spend a lot of time waiting to enter a monitor, look at the [Link] events in a
recording from Flight Recorder.
Look at the locks that are contended the most and the stack trace of the threads waiting to
acquire the lock. Typically, look for contention that you did not think would be an issue. Logging
is a common area that can be an unexpected bottleneck in some applications.
When you see performance degradation after a program update or at any specific times in the
Java application, take a flight recording when things are good, and take another one when
things are bad to look for a synchronization site that increases a lot.
Note:
By default, contention events with a duration longer than 20 ms are recorded. This
threshold can be modified when starting the flight recording. Shorter thresholds give
more events and also potentially more overhead. If you believe contention is an
issue, then you could take a shorter recording with a very low threshold of only a few
milliseconds. When this is done on a live application, make sure to start with a very
short recording, and monitor the performance overhead.
Note:
By default, contention events with a duration longer than 20 ms are recorded. This
threshold can be modified when starting the flight recording. Shorter thresholds give
more events and also potentially more overhead. If you believe contention is an
issue, then you could take a shorter recording with a very low threshold of only a few
milliseconds. When this is done on a live application, make sure to start with a very
short recording, and monitor the performance overhead.
4-8
Chapter 4
I/O Performance
I/O Performance
Flight recordings can help you diagnose I/O performance issues in Java application.
Topics:
• I/O Performance
• Use the Socket Read and Write Events to Debug I/O Issues
I/O Performance
When a Java application spends a lot of time reading or writing sockets or files, then I/O or
networking may be the bottleneck. Recordings from Flight Recorder can help identify problem
areas.
To diagnose I/O issues in applications, look at the following events in your flight recording.
Make sure that all of these events are enabled in the recording template that you are using:
• [Link]
• [Link]
• [Link]
• [Link]
Use the socket read and write information in your flight recording to calculate the number of
reads from a specific remote address, the total number of bytes read, and the total time spent
waiting. Look at each event to analyze the time spent and data read.
File or networking I/O issues are diagnosed in a similar fashion. Look at the files read to or
written to the most, then see each file read/write and the time spent on I/O.
By default, only events with a duration longer than 20 ms are recorded. When starting a flight
recording, you can lower the file I/O threshold or the socket I/O threshold to gather more data,
potentially with a higher performance effect.
Use the Socket Read and Write Events to Debug I/O Issues
When a Java application spends a lot of time reading or writing sockets or files, then I/O or
networking may be the bottleneck. Recordings from Flight Recorder can help identify problem
areas.
To diagnose I/O issues in applications, look at the following events in your flight recording.
Make sure that all of these events are enabled in the recording template that you are using:
• [Link]
• [Link]
• [Link]
• [Link]
Use the socket read and write information in your flight recording to calculate the number of
reads from a specific remote address, the total number of bytes read, and the total time spent
waiting. Look at each event to analyze the time spent and data read.
4-9
Chapter 4
Code Execution Performance
File or networking I/O issues are diagnosed in a similar fashion. Look at the files read to or
written to the most, then see each file read/write and the time spent on I/O.
By default, only events with a duration longer than 20 ms are recorded. When starting a flight
recording, you can lower the file I/O threshold or the socket I/O threshold to gather more data,
potentially with a higher performance effect.
Topics:
• Code Execution Performance
• Use [Link] and [Link] Events to Monitor Code Execution
Performance
4-10
Chapter 4
Code Execution Performance
taking a lot of CPU. In that case, look at the other applications running on the system using OS
tools such as Top or the task manager to find out which processes are using a lot of CPU.
In case your application is using a lot of CPU time, look at [Link] events and
identify the threads that use the most CPU time. This information is based on method
sampling, so it may not be 100% accurate if the sample count is low. When a recording is
running, the JVM samples the threads. By default, a continuous recording does only some
method sampling, while a profiling recording does as much as possible. The method sampling
gathers data from only those threads running code. The threads waiting for I/O, sleeping,
waiting for locks, and so on are not sampled. Therefore, threads with a lot of method samples
are the ones using the most CPU time; however, how much CPU is used by each thread is not
known.
The Hot Methods tab in the Code tab group helps find out where your application spends
most of the execution time. This tab shows all the samples grouped by top method in the stack.
Use the Call Tree tab to start with the lowest method in the stack traces and then move
upward. starts with [Link], and then looks at the calls that have been most sampled.
4-11
5
Troubleshoot Security APIs
To learn more about troubleshooting security APIs, see Troubleshooting Security.
5-1
Part II
Debug JVM Issues
This part describes causes and various debugging techniques for the following topics.
• Troubleshoot System Crashes
Provides guidance about specific procedures for troubleshooting system crashes.
• Troubleshoot Process Hangs and Loops
Provides guidance about specific procedures for troubleshooting hanging or looping
processes.
• Handle Signals and Exceptions
Provides guidance about signal and exception handling by Java HotSpot Server VM.
6
Troubleshoot System Crashes
This chapter presents information and guidance about some specific procedures for
troubleshooting system crashes.
A crash, or fatal error, causes a process to terminate abnormally. There are various possible
reasons for a crash. For example, a crash can occur due to a bug in the Java HotSpot VM, in a
system library, in a Java SE library or an API, in application native code, or even in the
operating system (OS). External factors, such as resource exhaustion in the OS can also
cause a crash.
Crashes caused by bugs in the Java HotSpot VM or in the Java SE library code are rare. This
chapter provides suggestions about how to examine a crash and work around some of the
issues (if possible) until the cause of the bug is diagnosed and fixed.
In general, the first step with any crash is to locate the fatal error log. This is a text file that the
Java HotSpot VM generates in the event of a crash. See Fatal Error Log for an explanation of
how to locate this file, as well as a detailed description of the file.
This chapter contains the following sections:
• Determine Where the Crash Occurred
• Find a Workaround
• Microsoft Visual C++ Version Considerations
6-1
Chapter 6
Determine Where the Crash Occurred
starting place. Consider the extract in the following example from the header of a fatal error
log.
In this case a SIGSEGV occurred with a thread executing in the library [Link].
In some cases a bug in a native library manifests itself as a crash in Java VM code. Consider
the crash in the following example where a JavaThread fails while in the _thread_in_vm state
(meaning that it is executing in Java VM code).
--------------- T H R E A D ---------------
In this case, although the problematic frame is a VM frame, the thread stack shows that a
native routine in [Link] has called into the VM (probably with JNI).
The first step to solving a crash in a native library is to investigate the source of the native
library where the crash occurred.
• If the native library is provided by your application, then investigate the source code of your
native library. A significant number of issues with JNI code can be identified by running the
6-2
Chapter 6
Determine Where the Crash Occurred
application with the -Xcheck:jni option added to the command line. See The -Xcheck:jni
Option.
• If the native library has been provided by another vendor and is used by your application,
then file a bug report against this third-party application and provide the fatal error log
information.
• If the native library where the crash occurred is part of the JDK (for example [Link],
[Link], and so forth), then it is possible that you encountered a library or API bug. If so,
gather as much data as possible, and submit a bug or report, indicating the library name.
You can find JDK libraries in the <java-home>/lib or <java-home>/bin directories of
the JDK distribution. See Submit a Bug Report.
You can troubleshoot a crash in a native application library by attaching the native debugger to
the core file or crash dump, if it is available. Depending on the OS, the native debugger is dbx,
gdb, or windbg. See Native Operating System Tools.
Note:
A complete thread stack is not available. The output line "error occurred during error
reporting" means that a problem arose trying to get the stack trace (this might
indicate stack corruption).
It might be possible to temporarily work around the issue by switching the compiler or by
excluding from compilation the method that provoked the crash.
See Working Around Crashes in the HotSpot Compiler Thread or Compiled Code.
6-3
Chapter 6
Determine Where the Crash Occurred
If the fatal error log output shows that the current thread is a VMThread, then look for the line
containing VM_Operation in the THREAD section. A VMThread is a special thread in the HotSpot
VM. It performs special tasks in the VM such as garbage collection (GC). If the VM_Operation
suggests that the operation is a GC, then it is possible that you encountered an issue such as
heap corruption.
Beside a GC issue, it could be something else (such as a compiler or runtime bug) that leaves
object references in the heap in an inconsistent or incorrect state. In this case, collect as much
information as possible about the environment and try possible workarounds. If the issue is
related to GC, then you might be able to temporarily work around the issue by changing the
GC configuration.
See Working Around Crashes During Garbage Collection.
On the other hand, C and C++ write beyond the end of the stack and cause a stack overflow.
This is a fatal error that causes the process to terminate.
In the HotSpot implementation, Java methods share stack frames with C/C++ native code,
namely user native code and the virtual machine itself. Java methods generate code that
checks whether the stack space is available at a fixed distance towards the end of the stack so
that the native code can be called without exceeding the stack space. The distance toward the
end of the stack is called shadow pages. The size of the shadow pages is between 3 and 20
pages, depending on the platform. This distance is tunable, so that applications with native
code needing more than the default distance can increase the shadow page size. The option to
increase shadow pages is -XX:StackShadowPages=n, where n is greater than the default
stack shadow pages for the platform.
If your application gets a segmentation fault without a core file or fatal error log file, see Fatal
Error Log. Or if you application gets a STACK_OVERFLOW_ERROR on Windows or the message "An
irrecoverable stack overflow has occurred," then this indicates that the value of
StackShadowPages was exceeded, and more space is needed.
If you increase the value of StackShadowPages, you might also need to increase the default
thread stack size using the -Xss parameter. Increasing the default thread stack size might
6-4
Chapter 6
Find a Workaround
decrease the number of threads that can be created, so be careful in choosing a value for the
thread stack size. The thread stack size varies by platform from 256 KB to 1024 KB.
--------------- T H R E A D ---------------
You can interpret the following information from the above example.
• The exception is EXCEPTION_STACK_OVERFLOW.
• The thread state is _thread_in_native, which means that the thread is executing native
or JNI code.
• In the stack information, the free space is only 4 KB (a single page on a Windows system).
In addition, the stack pointer (sp) is at 0x00041000, which is close to the end of the stack at
0x00040000.
• The printout of the native frames shows that a recursive native function is the issue in this
case. The output notation ...<more frames>... indicates that additional frames exist but
were not printed. The output is limited to 100 frames.
Find a Workaround
Possible workarounds if a crash occurs with a critical application.
If a crash occurs with a critical application, and the crash appears to be caused by a bug in the
HotSpot VM, then it might be desirable to quickly find a temporary workaround. If the crash
occurs with an application that is deployed with the most recent release of the JDK, then the
crash should be reported to Oracle.
6-5
Chapter 6
Find a Workaround
Important:
Even if a workaround in this section successfully eliminates a crash, the workaround
is not a fix for the problem, but merely a temporary solution. Place a support call or
file a bug report with the original configuration that demonstrated the issue.
The following are three scenarios to find workarounds for system crashes.
• Working Around Crashes in the HotSpot Compiler Thread or Compiled Code
• Working Around Crashes During Garbage Collection
• Working Around Crashes Caused by Class Data Sharing
Since the JDK 7u5 release, the HotSpot compiler is ignored by default. A command-line option
is available to simulate the old behavior, which is useful when multiple methods were excluded.
See notable bug fixes in JDK 7u5.
To exclude methods from being compiled by using a JVM flag instead of the .hotspot_compile
file, see the -XX:CompileCommand option in Advanced JIT Compiler Options for java in the
Java Development Kit Tool Specifications.
The following example shows a fragment of an error log for a compiler bug that was
encountered and fixed during development. The log file shows that the HotSpot Server VM is
used, and the crash occurred in CompilerThread1. In addition, the log file shows that the
current CompileTask was the compilation of the [Link] method.
6-6
Chapter 6
Find a Workaround
Current CompileTask:
opto: 11 [Link](I)V (53 bytes)
--------------- P R O C E S S ---------------
In general, the format of this file is excludeclassmethod, where class is the class (fully
qualified with the package name) and method is the name of the method. Constructor methods
are specified as <init> and static initializers are specified as <clinit>.
Note:
The.hotspot_compiler file is an unsupported interface. It is documented here solely
for the purposes of troubleshooting and finding a temporary workaround.
After the application is restarted, the compiler will not attempt to compile any of the methods
excluded in the .hotspot_compiler file. In some cases this can provide temporary relief until
the root cause of the crash is diagnosed and the bug is fixed.
In order to verify that the HotSpot VM correctly located and processed the .hotspot_compiler
file that is shown in the previous example from the second approach, look for the log
information at runtime.
6-7
Chapter 6
Find a Workaround
Note:
The file name separator is a dot, not a slash.
--------------- T H R E A D ---------------
Registers:
EAX=0x0000000a, EBX=0x00000001, ECX=0x00289530, EDX=0x00000000
ESP=0x02aefc2c, EBP=0x02aefc44, ESI=0x00289530, EDI=0x00289530
EIP=0x0806d17a, EFLAGS=0x00010246
6-8
Chapter 6
Find a Workaround
V [[Link]+0x71771]
V [[Link]+0xfd1d3]
V [[Link]+0x6cd99]
V [[Link]+0x504bf]
V [[Link]+0x6cf4b]
V [[Link]+0x1175d5]
V [[Link]+0x1170a0]
V [[Link]+0x11728f]
V [[Link]+0x116fd5]
C [[Link]+0x27fb8]
C [[Link]+0x1d33b]
Note:
A crash during garbage collection does not suggest a bug in the garbage collection
implementation. It could also indicate a compiler or runtime bug, or some other issue.
You can try the following workarounds if you repeatedly get a crash during garbage collection:
• Switch GC configuration. For example, if you are using the serial collector, then try the
throughput collector, or vice versa.
• If you are using the HotSpot Server VM, then try the HotSpot Client VM.
If you are not sure which garbage collector is in use, then you can use the jmap utility on the
Linux operating system. See The jmap Utility to get the heap information from the core file, if
the core file is available. In general, if the GC configuration is not specified on the command
line, then the serial collector will be used on Windows. On the Linux operating system, it
depends on the machine configuration. If the machine has at least 2 GB of memory and has at
least 2 CPUs, then the throughput collector (Parallel GC) will be used. For smaller machines,
the serial collector is the default. The option to select the serial collector is -
XX:+UseSerialGC and the option to select the throughput collector is -
XX:+UseParallelGC. If, as a workaround, you switch from the throughput collector to the
serial collector, then you might experience some performance degradation on multiprocessor
systems. This might be acceptable until the root issue is diagnosed and fixed.
6-9
Chapter 6
Microsoft Visual C++ Version Considerations
The fatal error log prints the version string in the header of the log. If sharing is enabled, it is
indicated by the text "sharing," as shown in the following example.
CDS can be disabled by providing the -Xshare:off option on the command line. If the crash
only occurs with sharing enabled, then it is possible that you encountered a bug in this feature.
In that case, gather as much information as possible and submit a bug report.
Note:
Use the java command option -Xinternalversion to determine which version of
Microsoft Visual Studio built the JDK. This version may vary depending on the JDK
release.
6-10
7
Troubleshoot Process Hangs and Loops
This chapter provides information and guidance about some specific procedures for
troubleshooting hanging or looping processes.
Problems can occur that involve hanging or looping processes. A hang can occur for many
reasons, but often stems from a deadlock in an application code, API code, or library code. A
hang can be due to a bug in the Java HotSpot VM.
Sometimes an apparent hang turns out to be, in fact, a loop. For example, a bug in a VM
process that causes one or more threads to go into an infinite loop can consume all available
CPU cycles.
The initial step when you diagnose a hang is to find out if the VM process is idle or consuming
all available CPU cycles. You can do this using a native operating system (OS) utility. If the
process appears to be busy and is consuming all available CPU cycles, then it is likely that the
issue is a looping thread rather than a deadlock.
This chapter contains the following sections:
• Diagnose a Loop Process
• Diagnose a Hung Process
If the application console (standard input/output) is available, then press the Control+\ key
combination (on Linux) or the Control+Break key combination (on Windows) to cause the
HotSpot VM to print a thread dump, including thread state. On Linux operating systems the
thread dump can also be obtained by sending a SIGQUIT to the process (command kill -QUIT
pid). In this case, the thread dump is printed to the standard output of the target process. The
output might be directed to a file, depending on how the process was started.
If the Java process is started with the -XX:+PrintClassHistogram command-line option,
then the Control+Break handler will produce a heap histogram.
If a thread dump can be obtained, then a good place to start is the thread stacks of the threads
that are in the RUNNABLE state. See Thread Dump for more information about the format of the
thread dump, as well as a table of the possible thread states in the thread dump. In some
cases, it might be necessary to get a sequence of thread dumps in order to determine which
threads appear to be continuously busy.
If the application console is not available (for example, the process is running in the
background, or the VM output is directed to an unknown location), then the jstack utility or the
jhsdb jstack utility can be used to get the stack thread. See The jstack Utility or the jstack
mode of jhsdb for more about the output of these utilities. The jstack utility or the jhsdb
jstack utility should also be used if the thread dump does not provide any evidence that a
Java thread is looping.
7-1
Chapter 7
Diagnose a Hung Process
When reviewing the output of the jstack utility, focus initially on the threads that are in the
RUNNABLE state. This is the most likely state for threads that are busy and possibly looping. It
might be necessary to execute jstack a number of times to get a better idea of which threads
are looping. If a thread appears to be always in the RUNNABLE state, then use jhsdb jstack
with the --mixed option to print the native frames and provide a further hint about what the
thread is doing. If a thread appears to be looping continuously while in the RUNNABLE state, then
this situation can indicate a potential HotSpot VM bug that needs further investigation.
If the VM does not respond to Control+\, then this could indicate a VM bug rather than an issue
with the application or library code. In this case, use jhsdb jstack with the --mixed option to
get a thread stack for all threads. The output will include the thread stacks for VM internal
threads. In this stack trace, identify threads that do not appear to be waiting. If it appears that
the looping is caused by a VM bug, then collect as much data as possible and submit a bug
report. See Submit a Bug Report for more about data collection.
Deadlock Detected
If a deadlock is detected, then it will be printed along with the stack trace of the threads
involved in the deadlock.
The following example shows the stack trace for this situation.
7-2
Chapter 7
Diagnose a Hung Process
Found 1 deadlock.
7-3
Chapter 7
Diagnose a Hung Process
The default deadlock detection works with locks that are obtained using the synchronized
keyword, as well as with locks that are obtained using the [Link] package. If
the Java VM flag -XX:+PrintConcurrentLocks is set, then the stack trace also shows a
list of lock owners.
If a deadlock is detected, then you must examine the output in more detail in order to
understand the deadlock. In the previous example, the thread main is locking object
0xf0c30560 and is waiting to enter 0xf0c41ec8, which is locked by thread AWT-EventQueue-0.
However, thread AWT-EventQueue-0 is waiting to enter 0xf0c30560, which is locked by main.
The detail in the stack traces provides information to help you find the deadlock.
No Thread Dump
If the VM is deadlocked or hung, use the jstack or jhsdb jstack command.
If the VM does not respond to Control+\ or Control+Break, then it is possible that the VM is
deadlocked or hung for some other reason. In that case, use The jstack Utility or the jstack
mode of jhsdb to get a thread dump. This also applies in the case when the application is not
accessible, or the output is directed to an unknown location.
In the thread dump, examine each of the threads in the BLOCKED state. The top frame can
sometimes indicate why the thread is blocked (for example, [Link] or [Link]).
The rest of the stack will give an indication of what the thread is doing. This is particularly true
when the source is compiled with line number information (the default), and you can cross-
reference the source code.
If a thread is in the BLOCKED state and the reason is not clear, then use jhsdb jstack --mixed
to get a mixed stack. With the mixed stack output, it should be possible to identify why the
thread is blocked. If a thread is blocked trying to enter a synchronized method or block, then
you will see frames such as ObjectMonitor::enter near the top of the stack. The following
example shows a sample, mixed-stack output.
Threads in the RUNNABLE state might also be blocked. The top frames in the mixed stack should
indicate what the thread is doing.
7-4
Chapter 7
Diagnose a Hung Process
One specific thread to check is VMThread. This is the special thread used to execute operations
like garbage collection (GC). It can be identified as the thread that is executing
VMThread::run() in its initial frames. On Linux, it should be identifiable using the C++ mangled
name _ZN8VMThread4loopEv.
7-5
8
Handle Signals and Exceptions
This chapter provides information about how signals and exceptions are handled by the Java
HotSpot Virtual Machine. It also describes the signal chaining facility, available on the Linux
and macOS operating systems, which facilitates writing applications that must install their own
signal handlers.
This chapter contains the following sections:
• Handle Signals on Linux and macOS
• Handle Exceptions on Windows
• Signal Chaining
• Handle Exceptions Using the Java HotSpot VM
• Console Handlers
• Signals Used in Linux and macOS
On Windows, the mechanism for handling both hardware and software exceptions is called
structured exception handling (SEH). This is stack frame-based exception handling similar to
the C++ and Java exception handling mechanism. In C++, the __try and __except keywords
8-1
Chapter 8
Handle Exceptions on Windows
are used to guard a section of code that might result in an exception, as shown in the following
example.
__try {
// guarded body of code
} __except (filter-expression) {
// exception-handler block
}
The __except block is filtered by a filter expression that uses the integer exception code
returned by the GetExceptionCode() API, exception information returned by the
GetExceptionInformation() API, or both.
__try {
// guarded body of code
} __finally {
// __finally block
}
When control leaves the __try block (after an exception or without an exception), the
__finally block is executed. Inside the __finally block, the AbnormalTermination() API
can be called to test whether control continued after the exception or not.
Windows programs can also install a top-level unhandled exception filter function to catch
exceptions that are not handled in the __try/__except block. This function is installed on a
process-wide basis using the SetUnhandledExceptionFilter() API. If there is no
handler for an exception, then UnhandledExceptionFilter() is called, and this will call
the top-level unhandled exception filter function, if any, to catch that exception. This function
also shows a message box to notify the user about the unhandled exception.
Windows exceptions are comparable to UNIX synchronous signals that are attributable to the
current execution stream. In Windows, asynchronous events such as console events (for
example, the user pressing Control+C at the console) are handled by the console control
handler registered using the SetConsoleCtlHandler() API.
8-2
Chapter 8
Signal Chaining
If an application uses the signal() API on Windows, then the C runtime library (CRT) maps
both Windows exceptions and console events to appropriate signals or C runtime errors. For
example, CRT maps Control+C to SIGINT and all other console events to SIGBREAK. Similarly, if
you register the SIGSEGV handler, CRT translates the corresponding exception to a signal. CRT
startup code implements a __try/__except block around the main() function. The CRT's
exception filter function (named _XcptFilter) maps the Win32 exceptions to signals and
dispatches signals to their appropriate handlers. If a signal's handler is set to SIG_DFL (default
handling), then _XcptFilter calls UnhandledExceptionFilter.
The vectored exception handling mechanism can also be used. Vectored handlers are not
frame-based handlers. A program can register zero or more vectored exception handlers using
the AddVectoredExceptionHandler API. Vectored handlers are invoked before structured
exception handlers, if any, are invoked, regardless of where the exception occurred.
The vectored exception handler returns one of the following values:
• EXCEPTION_CONTINUE_EXECUTION: Skip the next vectored and SEH handlers.
• EXCEPTION_CONTINUE_SEARCH: Continue to the next vectored or SEH handler.
Signal Chaining
Signal chaining enables you to write applications that need to install their own signal handlers.
This facility is available on Linux and macOS.
The signal chaining facility has the following features:
• Support for preinstalled signal handlers when you create Oracle’s HotSpot Virtual Machine.
When the HotSpot VM is created, the signal handlers for signals that are used by the
HotSpot VM are saved. During execution, when any of these signals are raised and are not
to be targeted at the HotSpot VM, the preinstalled handlers are invoked. In other words,
preinstalled signal handlers are chained behind the HotSpot VM handlers for these signals.
• Support for the signal handlers that are installed after you create the HotSpot VM, either
inside the Java Native Interface code or from another native thread.
Your application can link and load the [Link] shared library before the libc/
libthread/libpthread library. This library ensures that calls to sigaction() are
intercepted and don’t replace the signal handlers that are used by the HotSpot VM, if the
handlers conflict with the signal handlers that are already installed by HotSpot VM. Instead,
these calls save the new signal handlers. The new signal handlers are chained behind the
HotSpot VM signal handlers for the signals. During execution, when any of these signals
are raised and are not targeted at the HotSpot VM, the preinstalled handlers are invoked.
If support for signal handler installation after the creation of the VM is not required, then the
[Link] shared library is not needed.
To enable signal chaining, perform one of the following procedures to use the [Link]
shared library:
– Link the [Link] shared library with the application that creates or embeds the
HotSpot VM:
8-3
Chapter 8
Handle Exceptions Using the Java HotSpot VM
* C shell (csh):
The interposed sigaction() call returns the saved signal handlers, not the signal handlers
installed by the HotSpot VM and seen by the operating system.
Note:
The SIGQUIT, SIGTERM, SIGINT, and SIGHUP signals cannot be chained. If the
application must handle these signals, then consider using the —Xrs option.
Note:
The library file name on macOS is [Link] not [Link] as it is on Linux.
It also installs the Win32 SEH using a __try /__except block in C++ around the thread
(internal) start function call for each thread created.
Finally, it installs an exception handler around JNI functions.
If an application must handle structured exceptions in JNI code, then it can use __try /
__except statements in C++. However, if it must use the vectored exception handler in JNI
code, then the handler must return EXCEPTION_CONTINUE_SEARCH to continue to the VM's
exception handler.
In general, there are two categories in which exceptions happen:
8-4
Chapter 8
Console Handlers
• When exceptions are expected and handled. Examples include the implicit null handling
cited, previously where accessing a null causes an EXCEPTION_ACCESS_VIOLATION, which is
handled.
• Unexpected exceptions. An example is an EXCEPTION_ACCESS_VIOLATION when executing
in VM code, in JNI code, or in native code. In these cases, the signal is unexpected, and
fatal error handling is invoked to create the error log and terminate the process.
Console Handlers
This topic describes a list of console events that are registered with the Java HotSpot VM.
The Java HotSpot VM registers console events, as shown in Table 8-1.
CTRL_BREAK_EVENT SIGBREAK This event and signal is used to dump Java stack
traces at the standard error stream. (Optional)
If an application must register its own console handler, then the -Xrs option can be used. With
this option, shutdown hooks are not run on SIGTERM (with the previously shown mapping of
events), and thread dump support is not available on SIGBREAK (with the above mapping of the
Control+Break event).
Signal Description
SIGSEGV, SIGBUS, SIGFPE, SIGPIPE, SIGILL These signals are used in the implementation for
implicit null check, and so forth.
SIGQUIT This signal is used to dump Java stack traces to the
standard error stream. (Optional)
SIGTERM, SIGINT, SIGHUP These signals are used to support the shutdown
hook mechanism
([Link]) when
the VM is terminated abnormally. (Optional)
SIGUSR2 This signal is used internally on Linux and macOS.
SIGABRT The HotSpot VM does not handle this signal.
Instead, it calls the abort function after fatal error
handling. If an application uses this signal, then it
should terminate the process to preserve the
expected semantics.
8-5
Chapter 8
Signals Used in Linux and macOS
Signals tagged as "optional" are not used when the -Xrs option is specified to reduce signal
usage. With this option, fewer signals are used, although the VM installs its own signal handler
for essential signals such as SIGSEGV. Specifying this option means that the shutdown hook
mechanism will not execute if the process receives a SIGQUIT, SIGTERM, SIGINT, or SIGHUP.
Shutdown hooks will execute, as expected, if the VM terminates normally (that is, when the last
non-daemon thread completes or the [Link] method is invoked).
SIGUSR2 is used to implement, suspend, and resume on Linux and macOS. However, it is
possible to specify an alternative signal to be used instead of SIGUSR2. This is done by
specifying the _JAVA_SR_SIGNUM environment variable. If this environment variable is set, then
it must be set to a value larger than the maximum of SIGSEGV and SIGBUS.
8-6
Part III
Debug Core Library Issues
This part describes issues and troubleshooting techniques that arise with time zone settings
and contains the following topic.
• Time Zone Settings in the JRE
Describes some issues that arise with time zone settings with the Java Runtime
Environment (JRE) and troubleshooting techniques to resolve these issues.
9
Time Zone Settings in the JRE
This chapter describes some issues that can arise with time zone settings with the Java
Runtime Environment (JRE) on the Windows operating system. It further describes
troubleshooting techniques and workarounds to solve these issues.
This chapter contains the following sections:
• Native Time Zone Information and the JRE
• Determine the Default Time Zone on Windows
Operating system-specific patches might be required to ensure that the correct system time is
delivered to the JRE.
The following sections describe troubleshooting techniques for time zone settings.
• Determine the Time Zone Data Version in Use
• Troubleshoot Problems with Java Time Zone Updater Tool
9-1
Chapter 9
Native Time Zone Information and the JRE
To determine the current time zone data version of your Java runtime using the tzupdater tool,
run the tool with the -V option as shown in the following example:
You can download the tzupdater tool from this web page: Timezone Updater Tool.
The likely cause is that you are using a Java runtime that is not from Oracle. Oracle provides a
Java runtime for Linux (x64), Microsoft Windows (x64), and macOS (x64). Oracle does not
provide the Java runtime for other platforms.
The output of running the java -version command does not provide enough information to
determine the actual vendor of a Java runtime. However, running tzupdater in update mode
with the -v option does print out the [Link] property. The following example shows the
result of running tzupdater when the environment is HP_UX from Hewlett Packard.
root@my_server:/opt/java6/bin> uname -a
HP-UX my_server B.11.23 U ia64 1114591084 unlimited-user license
root@my_server:/opt/java6/bin> ./java -version
java version "[Link]"
Java(TM) SE Runtime Environment (build [Link]-jinteg_14_oct_2009_01_44-b00)
Java HotSpot(TM) Server VM (build 14.2-b01-jre1.6.0.05-rc5, mixed mode)
root@my_server:/opt/java6/bin> ./java -jar [Link] -v -l
[Link]: /opt/java6/jre
[Link]: Hewlett-Packard Co.
[Link]: [Link]
JRE tzdata version: tzdata2009i
There's no tzdata available for this Java runtime.
In the previous example, [Link] is set to “Hewlett-Packard Co." The Java runtime that
you are trying to update using tzupdater is not supported by Oracle.
A possible solution is to visit the website of your Java runtime vendor and determine whether a
time zone updater tool is available.
9-2
Chapter 9
Determine the Default Time Zone on Windows
You can save the code snippet in the previous example to a file named [Link]
and compile it using the javac command. Then, you can run the compiled DefaultTimeZone
class, as shown in the following example.
In the previous example, the default time zone is Europe/Berlin. Running the program should
display your local time zone. If the output is not the expected time zone, then continue with the
following troubleshooting steps.
9-3
Chapter 9
Determine the Default Time Zone on Windows
Note:
It is a good practice to back up the Windows registry before reviewing or editing
it. If you make a mistake, you can damage the Windows registry.
To enable the automatic adjustment of daylight saving time from the Windows registry:
1. Click the Windows Start button.
2. In the Search programs and files field, enter regedit and then press Enter to open the
Registry Editor.
3. In the Registry Editor, search for the key DynamicDaylightTimeDisabled and look at
the setting.
If the registry setting is 1, then dynamic daylight time is disabled.
If the registry setting is 0, then dynamic daylight time is enabled.
If you prefer, you can access the Windows registry from the Windows command window.
In the following example, the registry setting is 1. With this setting, the clock is not
automatically adjusted for daylight saving time.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation]
"DynamicDaylightTimeDisabled"=dword:00000001
If you disable the DynamicDaylightTimeDisabled option, then Java returns a GMT (Greenwich
Mean Time) offset and not a time zone ID that is compatible with the uniform naming
convention (such as "Europe/Berlin"). For example, the offset will be expressed as GMT+01
and not "Europe/Berlin."
9-4
Chapter 9
Determine the Default Time Zone on Windows
The corresponding value for the Registry key TimeZoneKeyName is “W. Europe Standard Time."
If setting a default time zone explicitly by specifying -[Link] works for the
DefaultTimeTestZone program, but does not work for your program, you should check whether
your code overwrites the default Java time zone during runtime with a method call such as this:
[Link](TimeZone zone)
9-5
Chapter 9
Determine the Default Time Zone on Windows
If you select the time zone called (UTC+01:00) Amsterdam, Berlin, Bern, Rome,
Stockholm, Vienna in the Windows Control Panel, then the relevant lines in the file
tzmappings are:
In this example, the Java runtime recognizes your default time zone (token number three)
based on your country. For example, if your country code is AD, then your default time zone is
"Europe/Andorra".
If there is no appropriate mapping entry in the tzmappings file, then it is possible that
Microsoft introduced a new time zone in a Windows update and that the new time zone is not
available to the Java runtime. In this situation, you can file a bug report, and request a new
entry in the tzmappings file from Oracle Java bugs website.
A similar disconnect between the operating system and the Java runtime is possible if you ran
the tool [Link]. This tool is provided by Microsoft, and allows users to add new time
zones. The Java runtime is unlikely to have a time zone introduced into the system by this tool.
Again, the solution is to file a bug to request that a new entry be added to the tzmappings
file.
9-6
Part IV
Debug Client Issues
This part describes Java client issues, troubleshooting techniques, and debugging tips for
client issues. The following topics are included.
• Introduction to Client Issues
Provides an overview of Java client technologies, describes Java client issues, and
troubleshooting tips.
• AWT
Provides guidance on specific procedures for debugging issues that occur with Java SE
Abstract Windows Toolkit (AWT).
• Java 2D Pipeline Rendering and Properties
Provides information and guidance for troubleshooting some of the most common issues
that might be found in the Java 2D API when changing pipeline rendering and properties.
• Java 2D
Provides guidance about troubleshooting some common issues found in Java 2D API.
• Swing
Provides guidance about troubleshooting some common issues found in Java SE Swing
API.
• Internationalization
Provides guidance about troubleshooting some issues found in Java Internationalization.
• Java Sound
Describes some issues and causes that happen with Java Sound technology and suggests
workarounds.
10
Introduction to Client Issues
This chapter explains how the different Java SE Desktop technologies interact with each other.
In addition, the chapter helps you to pinpoint the technology from which you might start
troubleshooting your problem and provides general troubleshooting tips.
This chapter contains the following sections:
• Java SE Desktop Technologies
• General Steps to Troubleshoot an Issue
• Identify the Type of Issue
• Basic Tools
• Java Debug Wire Protocol
This topic describes troubleshooting techniques for the following Java SE desktop
technologies:
• Abstract Window Toolkit (AWT) provides a set of application programming interfaces
(APIs) for constructing graphical user interface (GUI) components such as menus, buttons,
10-1
Chapter 10
General Steps to Troubleshoot an Issue
text fields, dialog boxes, check boxes, and for handling user input through those
components. In addition, AWT allows for rendering of simple shapes such as ovals and
polygons and enables developers to control the interface layout and fonts used by their
applications. It also includes data transfer classes (including drag and drop) that allow cut
and paste through the native platform clipboard.
The classes of this API are at the bottom of the software stack (closest to the underlying
operating and desktop system).
AWT also provides a set of heavyweight components.
Purely AWT applications are usually not related to Swing. If an AWT application does
custom rendering, it uses Java 2D.
• Java 2D is a set of classes for advanced 2D graphics and imaging. It encompasses line
art, text, and images in a single comprehensive model. The API provides extensive support
for image compositing and alpha channel images, a set of classes to provide accurate
color space definition and conversion, and a rich set of display-oriented imaging operators.
These classes are provided as additions to the [Link] and [Link] packages.
Like AWT, Java 2D is also at the bottom of the software stack (closest to the underlying
operating and desktop system).
• Swing provides a comprehensive set of GUI components and services which enables the
development of commercial-quality desktop and Internet/Intranet applications.
Swing is built on top of many of the other Java SE Desktop technologies, including AWT,
Java2D and Internationalization. In most cases the Swing high-level components are
recommended instead of those in AWT. However, there are many APIs in AWT that are
important to understand when programming in Swing.
Since Swing is a lightweight toolkit, it has very little interaction with the native platform.
Swing uses Java 2D for rendering, and AWT provides creation and manipulation of top-
level components, such as Windows, Frames, and Dialogs.
• Internationalization is the process of designing software so that it can be adapted
(localized) to various languages and regions easily, cost-effectively, and in particular
without engineering changes to the software. Localization is performed by simply adding
locale-specific components, such as translated text, data describing locale-specific
behavior, fonts, and input methods.
In Java SE, internationalization support is fully integrated into the classes and packages
that provide language-dependent or culture-dependent functionality.
To know more about internationalization APIs and features of Java SE, see
Internationalization Overview.
• Java Sound provides low-level support for audio operations such as audio playback and
capture (recording), mixing, musical instrument digital interface (MIDI) sequencing, and
MIDI synthesis in an extensible, flexible framework. This API is supported by an efficient
sound engine which guarantees high-quality audio mixing and MIDI synthesis capabilities
for the platform.
The better you understand the relationships between these technologies, the more quickly you
can pinpoint the area your problem falls into.
10-2
Chapter 10
Identify the Type of Issue
10-3
Chapter 10
Identify the Type of Issue
...
# Java VM: Java HotSpot(TM) Client VM (1.6.0-beta2-b76 mixed mode, sharing)
# Problematic frame:
# C [[Link]+0x123456]
...
If the crash occurred in the Java Native Interface (JNI), it was likely to have been caused by
the desktop libraries. A crash in a native library typically means a problem in Java 2D or AWT
because Swing does not have much native code. The small amount of native code in Swing is
then concerned with the native look and feel, and if your application is using native look and
feel, then the crash may be related to this area.
The error log usually shows the exact library where the crash occurred, and this can give you a
good idea of the cause. Crashes in libraries which are not part of the Java Development Kit
(JDK) usually indicate problems with the environment, for example, bad video drivers or
desktop managers.
Performance Problems
Performance problems are harder to diagnose because you generally do not have as much
information.
First, you must determine which technology has the problem. For example, rendering
performance problems are probably in Java 2D, and responsiveness issues can be Swing-
related.
Performance-related problems can be divided into the following categories:
• Startup
How long does the application take to start up and become useful to the user?
• Footprint
How much memory does the application take? This can be measured by tools such as
Task Manager on Windows or top and prstat on the Linux operating system.
• Runtime
How fast does the application complete the task it is designed to perform? For example, if
the application computes something, how long does it take to finish the computations? In
the case of a game, is the frame rate acceptable, and does the animation look smooth?
Note: This is not the same as responsiveness, which is the next topic.
10-4
Chapter 10
Identify the Type of Issue
• Responsiveness
How fast does the application respond to user interaction? If the user clicks a menu, how
long does it take for the menu to appear? Can a long-running task be interrupted? Does
the application repaint fast enough so that it does not appear to be slow?
Behavior Problems
This section provides guidance about dealing with various problems in the application.
In addition to crashes, various behavior-related problems can occur. Some of these problems
are listed below. Their descriptions can guide you to the Java SE Desktop technology to
troubleshoot.
• Hangs occur when the application stops responding to user input. See Troubleshoot
Process Hangs and Loops .
• Exceptions in Java code are visibly thrown to the console or the application log files. An
examination of this output will guide you to the problem area.
• Rendering and repainting issues indicate a problem in Java 2D or in Swing. For
example, the application’s appearance is incorrect after a repaint that was caused by
another application being dragged over it. Other examples are incorrect font, wrong colors,
scrolling, damaging the application's frame by dragging another window over it, and
updating a damaged area.
A quick test is the following: If the problem is reproducible on a different platform (for
example, the problem was originally seen on Windows, and it is also present on Linux), it is
very likely to be a Swing PaintManager problem.
For the ways to change the Java 2D rendering pipelines with some flags, see Java 2D.
This can also help determine if the problem is related to Java 2D or to Swing.
Multiscreen-related repainting issues belong to Java 2D (for example, repainting problems
when moving a window from one screen to another, or other unusual behavior caused by
the interaction with a non-default screen device).
• Issues related to desktop interaction indicate a problem in AWT. Some examples of
such issues occur when moving, resizing, minimizing and maximizing windows, handling
focus, enumerating multiple screens, using modality, interacting with the notification area
(system tray), and viewing splash screens.
• Drag-and-drop problems are related to AWT.
• Printing problems could be related either to Java 2D or AWT depending on the API that is
used.
• Text-rendering issues in AWT applications might be a problem in font properties or in
internationalization.
However, if your application is purely AWT, text rendering problems might also be caused
by Java 2D. On Linux, text rendering is performed by Java 2D.
Text rendering in Swing is performed by Java 2D. Therefore, if your application uses Swing
and you have text rendering problems (such as missing glyphs, incorrect rendering of
glyphs, incorrect spacing between lines or characters, bad quality of font rendering), then
the problem is likely to be in Java 2D.
• Painting problems are most likely a Swing issue.
• Full-screen issues are related to the Java 2D API.
• Encoding and locales issues (for example, no locale-specific characters displayed)
indicate internalization problems.
10-5
Chapter 10
Basic Tools
Basic Tools
This section provides a list of basic tools that can help you troubleshoot certain types of issues.
This section lists a few tools that can help you troubleshoot certain types of issues.
• Performance: Benchmarks, profilers, DTrace, Java probe.
• FootPrint: jmap, profilers
• Crashes: Native debuggers
• Hangs: JConsole, jstack, Control+Break
java -Xdebug -
Xrunjdwp:transport=dt_shmem,address=debug,server=y,suspend=y Test
java -Xdebug -
Xrunjdwp:transport=dt_socket,address=8888,server=y,suspend=y Test
The Test class will start in the debugging mode and wait for a debugger to attach to it at
address debug (on Windows) or 8888 (on the Linux operating system).
3. Open another command line, and use the following command to run jdb and attach it to
the running debug server:
• On Windows:
After jdb initializes and attaches to Test, you can perform Java-level debugging.
4. Set your breakpoints and run the application. For example, to set the breakpoint at the
beginning of the main method in Test, run the following command:
10-6
Chapter 10
Java Debug Wire Protocol
When the jdb utility hits the breakpoint, you will be able to inspect the environment in
which the application is running and see if it is functioning as expected.
5. (Optional) To perform native-level debugging along with Java-level debugging, use native
debuggers to attach to the Java process running with JDWP.
• On Linux, you can use the gdb utility.
• On Windows, you can use Visual Studio for native-level debugging as follows:
a. Open Visual Studio.
b. On the Debug menu, select Attach to Process. Select the Java process that is
running with JDWP.
c. On the Project menu, select Settings, and open the Debug tab. In the Category
drop-down list, select Additional DLLs and add the native DLL that you want to
debug (for example, [Link]).
d. Open the source file (one or more) of [Link] and set your breakpoints.
e. Enter cont in the jdb window. The process will hit the breakpoint in Visual Studio.
10-7
11
AWT
This chapter provides information and guidance about some specific procedures for
troubleshooting common issues that might occur in the Java SE Abstract Window Toolkit
(AWT).
This chapter contains the following sections:
• Debug Tips for AWT
• Layout Manager Issues
• Key Events
• Modality Issues
• AWT Crashes
• Focus Events
• Data Transfer
• Other Issues
• Heavyweight or Lightweight Components Mix
Loggers can produce helpful output when debugging AWT problems. See [Link]
package description.
The following loggers are available:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link].X11
11-1
Chapter 11
Layout Manager Issues
Key Events
Some issues related to handling key events do not have a solution in the current release.
Modality Issues
This section provides information about issues related to using modality.
The section addresses the following issues.
• UNIX window managers:
Many of the modality improvements are unavailable in some Linux environments, for
example, when using Common Desktop Environment (CDE) window managers. To see if a
11-2
Chapter 11
AWT Crashes
modality type or modal exclusion type is supported in a particular configuration, use the
following methods:
– [Link]()
– [Link]()
When a modal dialog box appears on the screen, the window manager might hide some of
the Java top-level windows in the same application from the taskbar. This can confuse end
users, but it does not affect their work much, because all the hidden windows are modal
blocked and cannot be operated.
• Other modality problems:
For more information about modality-related features and how to use them, see the AWT
Modality specification.
One of the sections in that specification describes some AWT features that might be
related to or affected by modal dialog boxes: always-on-top property, focus handling,
window states, and so on. Application behavior in such cases is usually unspecified or
depends on the platform; therefore, do not rely on any particular behavior.
AWT Crashes
This section shows you how to identify and troubleshoot crashes related to AWT.
• Distinguish an AWT crash:
When a crash occurs, an error log is created with information and the state obtained at the
time of the crash. See Fatal Error Log.
A line near the top of the file indicates the library where the error occurred. The following
example shows part of the error log file in the case when the crash was related to the AWT
library.
...
# Java VM: Java HotSpot(TM) Client VM (1.6.0-beta2-b76 mixed mode, sharing)
# Problematic frame:
# C [[Link]+0x123456]
...
However, the crash can happen somewhere deep in the system libraries, although still
caused by AWT. In such cases, the indication [Link] does not appear as a problematic
frame, and you need to look further in the file, in the section Stack: Native frames: Java
frames as shown in the following example.
11-3
Chapter 11
Focus Events
j [Link]()V+0
j [Link]()V+69
j [Link]()V+11
v ~StubRoutines::call_stub
V [[Link]+0x83c86]
V [[Link]+0xd870f]
V [[Link]+0x83b48]
V [[Link]+0x838a5]
V [[Link]+0x9ebc8]
V [[Link]+0x108ba1]
V [[Link]+0x108b6f]
C [[Link]+0x27fb8]
C [[Link]+0x202ed]
If the text [Link] appears somewhere in the native frames, then the crash might be
related to AWT.
• Troubleshoot an AWT crash:
One of the possible causes of crashes is that many AWT operations are asynchronous.
For example, if you show a frame with a call to [Link](true), then you
cannot be sure that it will be the active window after the return from this call.
Another example concerns native file dialogs. It takes some time for the operating system
to initialize and show these dialogs, and if you dispose of them immediately after the call to
setVisible(true), then a crash might occur. Therefore, if your application contains
some AWT calls running simultaneously or immediately one after another, it is a good idea
to insert some delays between them or add some synchronization.
Focus Events
The following sections discuss the troubleshooting issues related to focus events:
• How to Trace Focus Events
• Native Focus System
• Focus Models Supported by X Window Managers
• Miscellaneous Problems with Focus
[Link]().addAWTEventListener(new AWTEventListener(
public void eventDispatched(AWTEvent e) {
[Link](e);
}
11-4
Chapter 11
Focus Events
), FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK |
WindowEvent.WINDOW_EVENT_MASK);
The [Link] stream is used here because it does not buffer the output.
NOT_SUPPORTED:
The correct order of focus events is the following:
• FOCUS_LOST on component losing focus
• WINDOW_LOST_FOCUS on top-level losing focus
• WINDOW_DEACTIVATED on top-level losing activation
• WINDOW_ACTIVATED on top-level becoming active widow
• WINDOW_GAINED_FOCUS on top-level becoming focused window
• FOCUS_GAINED on component gaining focus
When focus is transferred between components inside the focused window, only
FOCUS_LOST and FOCUS_GAINED events should be generated. When focus is
transferred between owned windows of the same owner or between an owned
window and its owner, then the following events should be generated:
• FOCUS_LOST
• WINDOW_LOST_FOCUS
• WINDOW_GAINED_FOCUS
• FOCUS_GAINED
Note:
The events losing focus or activation should come first.
11-5
Chapter 11
Focus Events
focus proxy. Now, it proxies focus not only for components in an owned window but for all child
components as well. A simple window never receives native focus and relies on the focus
proxy of its owner. This mechanism is transparent for a user but should be taken into account
when debugging.
On the Linux operating system, XToolkit uses a focus model that allows AWT to manage focus
itself. With this model the window manager does not directly set input focus on a top-level
window, but instead it sends only the WM_TAKE_FOCUS client message to indicate that focus
should be set. AWT then explicitly sets focus on the top-level window if it is allowed.
Note:
The X server and some window managers may send focus events to a window.
However, these events are discarded by AWT.
AWT does not generate the hierarchical chains of focus events when a component inside a
top-level gains focus. Moreover, the native window mapped to the component does not get a
native focus event. On the Linux platform, as well as on the Windows platform, AWT uses the
focus proxy mechanism. Therefore, focus on the component is set by synthesizing a focus
event, whereas the invisible focus proxy has native focus.
A native window that is mapped to a Window object (not a Frame or Dialog object) has the
override-redirect flag set. Thus, the window manager does not notify the window about the
focus change. Focus is requested on the window only in response to a mouse click. This
window will not receive native focus events at all. Therefore, you can trace only FocusIn or
FocusOut events on a frame or dialog box. Because the major processing of focus occurs at
the Java level, debugging focus with XToolkit is simpler than with WToolkit.
11-6
Chapter 11
Focus Events
11-7
Chapter 11
Data Transfer
Note:
This approach does not work for the window, only for the frame or dialog box.
Data Transfer
The following sections discuss possible problems with data transfer features, which allow you
to add drag-and-drop (DnD) and cut, copy, and paste (CCP) operations to the application.
• Debug Drag-and-Drop Applications
• Frequent Issues with Data Transfer
11-8
Chapter 11
Data Transfer
new DataFlavor([Link] +
"; class=" +
(new String[0]).getClass().getName())
Solution: “Quote” the value of the representation class parameter, as shown in the
following example, where the quotation marks escape:
new DataFlavor([Link] +
"; class=" +
"\"" +
(new String[0]).getClass().getName() +
"\"")
11-9
Chapter 11
Other Issues
Solution: Use Swing's DnD support with Swing components. Although the Swing DnD
implementation is based on the AWT DnD implementation, you cannot mix Swing and
AWT DnD. See Lesson: Drag and Drop and Data Transfer in the Java Tutorials.
7. There is no way to change the state of the source to depend on the target.
In order to change the state of the source to depend on the target, you must have
references to the source and target components in the same area of code, but this is not
currently implemented in the DnD API.
Workaround: One workaround is to add flags to the transferable object that allow you to
determine the context of the event.
For the transfer of data within one Java VM, the following workaround is proposed:
• Implement your target component as DragSourceListener.
• In [Link](), add the target at the
drag source listener, as shown in the following example.
[Link]().addDragSourceListener(target);
}
• Now you can get the target and the source in the dragEnter(), dragOver(),
dropActionChanged(), and dragDropEnd() methods of
DragSourceListener().
8. Transferring objects in an application takes a long time.
The transferring of a big bundle of data or the creation of transferred objects takes too
long. The user must wait a long time for the data transfer to complete.
This expensive operation makes transferring too long because you must wait until
[Link]() finishes.
Solution: This solution is valid only for transferring data within one Java VM. Create or get
expensive resources before the drag operation. For example, get the file content when you
create a transferable data, so that [Link]() will not be too
long.
Other Issues
The following subsections discuss troubleshooting tips for other issues:
• Splash Screen Issues
• Tray Icon Issues
• Pop-up Menu Issues
• Background or Foreground Color Inheritance
• AWT Panel Size Restriction
• Hangs During Debugging of Pop-up Menus and Similar Components on X11
• [Link]()/toBack() Behavior on X11
11-10
Chapter 11
Other Issues
11-11
Chapter 11
Other Issues
-[Link]=true
This property effectively turns off setting the grab, and does not hang the system. However,
with this option set, in some cases, this can lead to the inability to terminate a GUI actions that
would normally be terminated. For example, pop-up menus may not be dismissed when
clicking a window's title bar.
11-12
Chapter 11
Heavyweight or Lightweight Components Mix
Note:
This workaround is not guaranteed to work because window managers can enforce
more restrictions. Also, setting a window to "always on top" is available to trusted
applications only.
However, native applications experience similar issues, and this peculiarity makes
Java applications behave similar to native applications.
[Link](myFont);
[Link]();
Note:
Swing applications and the Swing library often use the following pattern:
[Link](myFont);
[Link]();
• Validate roots:
The concept of validate roots mentioned in Validate the component hierarchy was
introduced in Swing in order to speed up the process of validating component hierarchies
because it may take a significant amount of time. While such optimization leaves upper
11-13
Chapter 11
Heavyweight or Lightweight Components Mix
parts of hierarchies invalid, this did not create any issues because the layout of
components inside a validate root does not affect the layout of the outside component
hierarchy (that is, the siblings of the validate root). However, when HW and LW
components are mixed together in a hierarchy, this statement is no longer true. That is why
the feature requires the whole component hierarchy to be valid.
Calling [Link]() may be inefficient, and AWT supports an alternative,
optimized way of handling invalidation/validation of component hierarchies. This feature is
enabled with a system property:
-[Link]=true
Once this property is specified, the invalidate() method will stop invalidation of the
hierarchy when it reaches the nearest validate root of a component on which the
invalidate() method has been invoked. Afterward, to restore the validity of the
component hierarchy, the application should simply call:
[Link]();
Note:
In this case, calling [Link]() would be effectively a no-op (a
statement that does nothing) because frame is still valid. Since some applications
rely on calling validate() directly on a component upper than the validate root
of the hierarchy (for example, a frame), this new optimized behavior may cause
incompatibility issues, and hence it is available only when specifying the system
property.
If an application experiences any difficulties running in this new optimized mode, a user
can use the key combination Control+Shift+F1 as described in Debug Tips for AWT to
investigate what parts of the component hierarchy are left invalid, and thus possibly cause
the problems.
• Swing painting optimization:
By default, the Swing library assumes that there are no HW components in the component
hierarchy, and therefore uses optimized drawing techniques to boost performance of the
Swing GUI. If a component hierarchy contains HW components, the optimizations must be
turned off. This is relevant for Swing JScrollPanes in the first place. You can change the
scrolling mode by using the [Link](int) method.
• Non-opaque LW components:
Non-opaque LW components are not supported by the HW/LW mixing feature
implementation by default. In order to enable mixing non-rectangular LW components with
HW components, the application must use the
[Link]() non-public
API.
11-14
Chapter 11
Heavyweight or Lightweight Components Mix
Note:
The non-rectangular LW components should still paint themselves using either
opaque (alpha = 1.0) or transparent (alpha = 0.0) colors. Using translucent colors
(with 0.0 < alpha < 1.0) is not supported.
-[Link]=true
11-15
12
Java 2D Pipeline Rendering and Properties
This chapter provides information and guidance for troubleshooting some of the most common
issues that might be found in the Java 2D API when changing pipeline rendering and
properties.
For a summary of Java 2D properties, see Java 2D Properties.
By choosing a different pipeline, or manipulating the properties of a pipeline, you might be able
to determine the cause of the problem, and often find a workaround.
In general, you can troubleshoot Java 2D pipeline issues by determining the default pipeline
used in your configuration. Then, either change the pipeline to another one, or modify the
properties of the default pipeline.
If the problem disappears, then you found a workaround. If the problem persists, then try
changing another property or pipeline.
Java 2D uses a set of pipelines, which can be roughly defined as different ways of rendering
the primitives. These pipelines are as follows:
• Linux: X11 Pipeline is the default for the Linux operating system.
• Windows OS: DirectDraw/GDI Pipeline is the default on Windows
• Windows OS: Direct3D Pipeline in Full-Screen Mode is an alternative on Windows.
• OpenGL Pipeline in Linux and Windows is an alternative on the Linux operating system, as
well as Windows.
Note:
The default pipeline is the XRender graphics pipeline.
These types of images can be put into X11 pixmaps for improved performance, especially in
the case of the Remote X server.
In addition, in certain cases, Java 2D uses X server extensions, for example, the MIT X shared
memory extension, or Direct Graphics Access extension, Double-buffer extension for double-
buffering when using the BufferStrategy API.
An additional pipeline, the OpenGL pipeline, might offer greater performance in some
configurations.
The following are X11 pipeline properties to troubleshoot.
• X11 Pipeline Pixmaps Properties
12-1
Chapter 12
Linux: X11 Pipeline
Note:
The shared memory pixmaps can only be used in the case of a local X server.
The advantage of using shared memory pixmaps is that the pipeline can get direct access
to the pixels in the pipeline, bypassing the X11 protocol, which results in better
performance.
By default, an image is stored in a normal X server pixmap, but it can be later moved to a
shared memory pixmap if the pipeline detects excessive reading from such an image. The
image can be moved back to a server pixmap if it is copied from often enough.
The pipeline allows two ways of controlling the use of shared memory pixmaps: either
disabling them or forcing all images to be stored in shared memory pixmaps.
First, try forcing the shared memory pixmaps because it often improves performance.
However, with certain video board/driver configurations, it may be necessary to disable the
shared memory pixmaps to avoid rendering artifacts or crashes.
12-2
Chapter 12
Windows OS: DirectDraw/GDI Pipeline
12-3
Chapter 12
Windows OS: Direct3D Pipeline in Full-Screen Mode
In general, the DirectDraw pipeline attempts to place the offscreen surfaces in the
framebuffer's video memory, which provides the fast copies from these surfaces to the
screen or other accelerated surfaces, as well as hardware accelerated rendering of certain
graphics operations.
To limit the effect of unaccelerated rendering to VRAM-based surfaces, there exists a
punting mechanism, which moves the surface that is detected to be often read from to the
system memory. If the surface is found to be copied from often enough, it may be
promoted back to video memory.
However, if the pipeline cannot perform an operation using the DirectDraw API (operations
using, for example, alpha compositing, or transforms, or antialiasing), then rendering is
performed using the software pipeline. In some cases, this means that the pixels of the
destination surface, which resides in VRAM, must be read into system memory, which is a
very expensive operation.
On certain video boards/drivers combinations, the system-memory-based DirectDraw
surfaces are known to cause rendering artifacts and other issues. The DirectDraw pipeline
provides a way to disable the punting mechanism so that the system memory surfaces are
not used.
To defeat the built-in surface punting mechanism, provide the following flag to the Java
VM: -[Link]=true.
Note:
This mechanism can result in performance degradation because the software
loops may be reading pixels from VRAM on each operation. In this case,
consider disabling the DirectDraw pipeline.
Note:
This operation might result in bad performance. Consider disabling the
DirectDraw pipeline instead.
12-4
Chapter 12
OpenGL Pipeline in Linux and Windows
Consider enabling the Direct3D pipeline for your application if it heavily uses rendering
operations such as alpha compositing, antialiasing, and transforms.
However, use caution when deciding to enable this pipeline in your application. For example,
some built-in video chipsets (which are used in most notebooks) do not perform well using
Direct3D, even if they satisfy the quality requirements for Java 2D pipelines.
The following are three cases to troubleshoot problems with Direct3D API.
1. Disable the Direct3D pipeline:
Some older video boards/drivers combinations are known to cause issues (both rendering
and performance) with the Direct3D pipeline. To disable the pipeline in these cases, pass
the parameter -Dsun.java2d.d3d=false to the Java VM, or set the J2D_D3D
environment variable to false.
2. Enable the Direct3D pipeline:
To enable the Direct3D pipeline in both windowed and full-screen mode, use the parameter
-Dsun.java2d.d3d=true, or set the J2D_D3D environment variable to true.
Note:
The pipeline is enabled only if the drivers support the minimum required features.
12-5
Chapter 12
OpenGL Pipeline in Linux and Windows
The following are use cases for troubleshooting problems in OpenGL pipeline.
• Enable OpenGL Pipeline
• Minimum Requirements
• Diagnose Startup Issues
• Diagnose Rendering and Performance Issues
• Latest OpenGL Drivers
To receive verbose console output about whether the OpenGL pipeline is initialized
successfully for a particular screen, set the option to True (note the uppercase T).
Minimum Requirements
The OpenGL pipeline will not be enabled if the hardware or drivers do not meet the minimum
requirements.
If one of the following requirements is not met, Java 2D will fall back and use the default
pipeline (X11 on Linux or GDI/DirectDraw on Windows), which means your application will
continue to work correctly, but without the OpenGL acceleration.
The minimum requirements for the Linux operating system are the following:
• Hardware accelerated OpenGL/GLX libraries installed and configured properly
• OpenGL version 1.2 or higher
• GLX version 1.3 or higher
• At least one TrueColor visual with an available depth buffer
The minimum requirements for Windows OS are the following:
• Hardware accelerated drivers supporting the extensions WGL_ARB_pbuffer,
WGL_ARB_render_texture, and WGL_ARB_pixel_format
• OpenGL version 1.2 or higher
• At least one pixel format with an available depth buffer
As previously mentioned, the OpenGL pipeline might not be enabled on certain machines for
various reasons. For example, the drivers might not be properly installed and might report an
insufficient version number. Alternatively, your machine might have an older graphics card that
does not support the appropriate OpenGL version or extensions.
12-6
Chapter 12
OpenGL Pipeline in Linux and Windows
You can get detailed information about the startup procedures of the OpenGL-based Java 2D
pipeline by using the J2D_TRACE_LEVEL environment variable, as shown in the following
examples.
Set the J2D_TRACE_LEVEL environment variable on Windows.
# set J2D_TRACE_LEVEL=4
# java -[Link]=True YourApp
# export J2D_TRACE_LEVEL=4
# java -[Link]=True YourApp
The output will be different depending on your platform and the installed graphics hardware,
but it can give you some insight into the reasons why the OpenGL pipeline is not being
successfully enabled for your configuration.
Note:
This output is especially useful when filing bug reports intended for the Java 2D
team.
Setting this property will cause Java 2D to fall back on the older pbuffer-based code path.
If you find that a certain Java 2D operation causes different visual results with the OpenGL
pipeline enabled than without, then it probably indicates a graphics driver bug. Similarly, if the
performance of Java 2D rendering is significantly worse with the OpenGL pipeline enabled
than without, then it is most likely caused by a driver or hardware problem.
In either case, file a detailed bug report through the normal bug reporting channels. See
Submit a Bug Report. When filing bug reports, be as detailed as possible, and include the
following information:
• Operating system (for example, Ubuntu Linux 6.06, Windows XP SP2)
12-7
Chapter 12
OpenGL Pipeline in Linux and Windows
• Name of graphics hardware manufacturer and device (for example, Nvidia GeForce 2 MX
440)
• Exact driver version (for example, ATI Catalyst 6.8, Nvidia 91.33)
• Output when J2D_TRACE_LEVEL=4 is specified on the command line (as described in the
previous section)
• The output of the glxinfo command if you are on Linux
12-8
13
Java 2D
This chapter provides information and guidance for troubleshooting some of the most common
issues that might be found in the Java 2D API.
This chapter contains the following sections:
• Generic Performance Issues
• Text-Related Issues
• Java 2D Printing
For a summary of Java 2D properties, see Java 2D Properties.
13-1
Chapter 13
Generic Performance Issues
One cause of performance issues is when operations performed are not hardware-accelerated.
Even in cases when a destination surface is accelerated, some primitives may not be.
It is important to know how to detect the cases when hardware acceleration is not being used.
Knowing this may help in improving performance.
Here are some of the common non-accelerated primitives in the default pipelines, and their
signatures in the tracing output.
Note:
Most of this tracing was taken on Linux; you may see some differences depending on
your platform and configuration.
[Link]$GeneralMaskBlit::Blit(IntArgb,SrcOverNoEa, "Integer
BGR Pixmap")[Link]::MaskBlit(IntArgb, SrcOver, IntBgr)
• Use of antialiasing (by setting the antialiasing hint). Sample primitive tracing output:
• Rendering antialiased text (setting the text antialising hint). Sample output can be one of
the following:
– [Link]::DrawGlyphListAA(OpaqueColor, SrcNoEa,
AnyInt)
– [Link]::DrawGlyphListLCD(AnyColor, SrcNoEa,
IntBgr)
13-2
Chapter 13
Generic Performance Issues
• Alpha compositing, either by rendering with translucent color (a color with an alpha value
that is not 0xff) or by setting a non-default AlphaCompositing mode with
[Link]():
[Link]$GeneralMaskBlit::Blit(IntArgb, SrcOver,
IntRgb)[Link]::MaskBlit(IntArgb, SrcOver, IntRgb)
]
• Non-trivial transforms (if the transform is more than only translation). Rendering a
transformed opaque image to a VolatileImage:
[Link]::TransformHelper(IntBgr, SrcNoEa,
IntArgbPre)
Run your application with tracing and ensure that you do not use unaccelerated primitives
unless they are needed.
Note:
This approach may limit your application's ability to take advantage of future
improvements in Java 2D's use of hardware acceleration.
For example, if your application is often used in remote X server cases, but it heavily uses
antialiasing, alpha compositing, and so forth, then the performance can be severely
degraded. To avoid this, disable the use of pixmaps by setting the -
[Link]=false property either by passing it to the Java runtime, or
by setting it programmatically using the [Link]() API.
13-3
Chapter 13
Generic Performance Issues
Note:
This property must be set before any GUI-related operations because it is read
only once.
13-4
Chapter 13
Text-Related Issues
The following API can be used to request the amount of available accelerated memory:
[Link]().
In addition, the following API can be used to determine if your image is being accelerated:
[Link]().
If you determined that your application is exhausting the resources, you can handle the
problem by not holding images you no longer need. For example, if your game advanced
to the next level, release all images from the previous levels. You can also release
accelerated resources associated with an image by using the [Link]() API.
You can also use the acceleration priority API [Link]()
and setAccelerationPriority() to specify the acceleration priority for your images.
It is a good idea to make sure that at least your back-buffer is accelerated, so create it first,
and with acceleration priority of 1 (default). You can also prohibit certain images from being
accelerated if needed by setting the acceleration priority to 0.0.
Text-Related Issues
This section describes possible issues and crashes that are related to text rendering and
describes tips to overcome such issues.
13-5
Chapter 13
Text-Related Issues
In this case, a particular font is probably the problem. If so, then removing this font from the
system will likely resolve the problem.
To identify the font file, execute the application with -[Link]=true. The
font that is mentioned last is usually the one that is causing problems, as shown in the
following example.
13-6
Chapter 13
Text-Related Issues
Note:
In some cases, the font that is last mentioned might not be the problem. Font names
are printed when they are first used and subsequent uses are not shown.
To verify that this particular font is causing the problem, you can temporarily remove it from
your system. You can easily find the file name associated with this particular family name from
the output.
If you found a font causing the JDK to crash, it is very important to report this problem,
including the particular font and the operating system in the Bugs Database. See Submit a Bug
Report.
13-7
Chapter 13
Java 2D Printing
Font Metrics
If you find that text bounds are different from what you expect, then ensure that you are using
the appropriate way to calculate them. For example, the height obtained from a FontMetrics is
not specific to a particular piece of text, and the stringWidth indicates logical advance, which
is not the same thing as wide. For more details, see the Font and Text questions in the Java
2D FAQ.
Java 2D Printing
This section describes some issues that can happen with Java 2D printing and suggests
causes and solutions.
See Printing questions in the Java 2D FAQ for additional help.
1. Java runtime crashes during printing on Windows.
Cause: The Java runtime uses Windows printer drivers, and they might have problems.
Solution: Upgrade the Windows printer driver for the printer that is being used.
2. The printing seems to be successful, but the job does not print on Windows.
Cause: Some jobs fail to properly spool to the printer.
Solution: In the printer driver properties, disable Advanced Printing Options.
3. The print dialog box takes a long time to appear on Windows.
Cause: Applications might cause the Java runtime to probe all printers, including those
that are disconnected.
Solution: Look for disconnected or unreachable network printers and remove them from
the list of printers.
4. [Link]() shows no service found error on Linux.
Cause: The cause is one of the following:
13-8
Chapter 13
Java 2D Printing
13-9
14
Swing
This chapter provides information and guidance on some specific procedures for
troubleshooting some of the most common issues that might be found in the Java SE Swing
API.
This chapter contains the following sections:
• General Debug Tips for Swing
• Specific Debug Tips for Swing
14-1
Chapter 14
Specific Debug Tips for Swing
Incorrect Threading
Random exceptions and painting problems are usually the result of incorrect threading usage
by Swing.
All access to Swing components, unless specifically noted in the JavaDoc API documentation,
must be done on the event dispatch thread. This includes any models (TableModel, ListModel,
and others) that are attached to Swing components.
The best way to check for bad usage of Swing is by using instrumented RepaintManager, as
illustrated in the following example.
14-2
Chapter 14
Specific Debug Tips for Swing
Display Update
Another source of painting problems can occur if you do not invoke repaint correctly when you
need to update the display.
14-3
Chapter 14
Specific Debug Tips for Swing
Changing a visible property of a Swing component, such as the font, will trigger a repaint or
revalidate. If you are writing a custom component, then you must invoke repaint and possibly
revalidate whenever the display or sizing information is updated. If you do not, the display will
only update the next time someone triggers a repaint.
A good way to diagnose this is to resize the window. If the content appears after a resize, then
that implies that the component did not invoke repaint or revalidate correctly.
Model Change
Invoke repaint when you change a visible property of a Swing component, but you need not
invoke repaint when your model changes.
If your model sends out the correct change notification, the JComponent will invoke repaint or
revalidate as appropriate.
However, if you change your model but do not send out a notification, then a repaint event may
not even work. In particular this will not work with JTree. The correct thing to do is to send the
appropriate model notification. This can usually be diagnosed by resizing the window and
noticing that the display did not update correctly.
Opaque Override
Another possible area of painting problems is if a component does not override opaque.
Further, if you do not invoke implementation you must honor the opaque property; that is, if this
component is opaque, you must completely fill in the background with a non-opaque color. If
you do not honor the opaque property, then you will likely see visual artifacts.
The only way to check for this is to look for consistent visual artifacts when the component
invokes repaint.
Note:
If you override the graphics in a subclass, then you should not make permanent
changes to the paint, paintComponent, or paintChildren passed in the Graphics
object. For example, you should not alter the clip Rectangle or modify the transform.
If you need to do these operations you may find it easier to create a new Graphics
object from the passed in Graphics object and manipulate it instead.
If you ignore this restriction, then the result will be clipping or other weird visual artifacts.
14-4
Chapter 14
Specific Debug Tips for Swing
The [Link] method ensures that painting happens to the double buffer. If you
override paint directly, then you may lose double buffering.
Possible Leaks
If the life cycle of your model is longer than that of a window with a component using the
model, you must explicitly set the model of the Swing component to null.
If you do not set the model to null, your model will retain a reference to the Component, which
will keep all components in the window from being garbage collected. Take a look at the
following example.
If your application still holds a reference to myModel, then frame and all its children will still be
reachable by way of the listener JTable installations on myModel. The solution is to invoke
[Link](new DefaultTableModel()).
14-5
Chapter 14
Specific Debug Tips for Swing
• [Link]().setLightWeightPopupEnabled(false)
Use Synth
Synth is an empty canvas.
To use Synth, you must either provide a complete XML file that configures the look and feel, or
extend SynthLookAndFeel and provide your own SynthStyleFactory.
This is easily reproduced with a composite component, like an editable JComboBox. Because a
JComboBox has child components that have a MouseListener, a MouseListener attached to an
editable JComboBox will never get notified.
If your MouseListener suddenly stops getting events, then it could be the result of a change in
the application whereby a descendant component now has a MouseListener. A good way to
check for this is to iterate over the descendants asking if they have any mouse listeners.
A similar scenario occurs with the KeyListener class. A KeyListener object is dispatched only
to the focused component.
The JComboBox case is another example of this situation. In the editable JComboBox case the
editor gets focus, not the JComboBox. As a result, a KeyListener attached to an editable
JComboBox will never get notified.
A component added to a top-level Swing component must go to the content pane, but the add
method (and a couple of other methods) on the JFrame, JWindow, and JDialog classes redirect
14-6
Chapter 14
Specific Debug Tips for Swing
The following methods redirect to the content pane for you: add (and its variants), remove
(and its variants), and setLayout.
This is purely a convenience, but can cause confusion. In particular, getChildren, getLayout,
and various others do not redirect to the content pane.
This change affects LayoutManagers that only work with one component, such as GroupLayout
and BoxLayout. For example, new GroupLayout(frame) will not work; instead, you must
use GroupLayout([Link]()).
Unlike the standard Windows file choosers, JFileChooser does not allow the user to follow
Windows shortcuts when browsing the file system, because it does not show the correct path
to the file.
To reproduce the problem, follow these steps:
1. Create a text file on the Desktop called, for example, [Link]. Open the text file and
type some text, for example: This is the contents of [Link].
2. Create a shortcut to the new text file in the following way: Drag the file with the right mouse
button to another location on the Desktop and choose Create Shortcut(s) here.
3. Run the JfileChooser test application, browse the Desktop, select Shortcut to
[Link] and click Open.
4. The result file is PathToDesktop\Shortcut to [Link], but it should be
PathToDesktop\[Link].
5. In addition, the contents of the result file in the text area shows the contents of the file
shortcut to [Link], but the contents should be This is the contents of
[Link], which was typed in step 1.
14-7
15
Internationalization
Information and guidance about troubleshooting issues that might be found in the area of
internationalization support.
For detailed information, visit the Internationalization Overview.
This chapter describes troubleshooting techniques for internationalization and localization.
• Troubleshoot Internationalization and Localization
15-1
16
Java Sound
This chapter describes some issues that can arise with the Java sound technology and
suggests causes and workarounds.
The following topic describes scenarios to troubleshoot Java sound problems.
• Troubleshoot Java Sound Issues
Audio formats
Java Sound supports various audio formats, but their availability depends on the operating
system. To use some audio format for recording or playing, the format must be supported by
your system (sound card drivers). Use supported formats as much as possible: PCM; 8 or 16
bits; 8000, 11025, 22050, 44100 Hz. The formats are supported by most sound cards. Most
sound cards support only PCM formats, and even if the driver supports mu-law, then it requires
some modification to the software. If you need to play or record mu-law data, then the
preferred way is to convert it to PCM format through a format converter.
See [Link] documentation for details about format conversion.
16-1
Chapter 16
Troubleshoot Java Sound Issues
16-2
Part V
Submit Bug Reports
The chapter Submit a Bug Report shows you how to submit a bug report. It includes
suggestions about what to try before submitting a report and which data to collect for the
report.
17
Submit a Bug Report
This chapter shows you how to submit a bug report. It includes suggestions about what to try
before submitting a report and which data to collect for the report.
This chapter contains the following sections:
• Check for Fixes in Update Releases
• Prepare to Submit a Bug Report
• Collect Data for a Bug Report
• Report a Bug
• Collect Core Dumps
17-1
Chapter 17
Collect Data for a Bug Report
• Search the Java Bug Database to see if this issue or a similar issue was reported. If the
issue has already been reported, then the bug report might have further information, such
as the following:
– If the issue was already fixed, then the release in which it was fixed is given.
– A workaround for the issue.
– Comments in the evaluation that explain, in further detail, the circumstances that
cause the issue to happen.
• If you conclude that the issue was not already reported, then report it at Report a Bug or
Request a Feature.
Before reporting an issue, verify that the environment where the problem happens is a
supported configuration. See Oracle JDK 23 Certified System Configurations.
In addition to the system configurations, check the list of supported locales. See JDK 23
Supported Locales.
17-2
Chapter 17
Collect Data for a Bug Report
• If the test case or problem requires third-party code, such as a commercial or open source
library or package, then provide then details about where and how to obtain the library.
Hardware Details
The hardware details are stored in the error logs when a fatal error occurs.
Sometimes, a bug happens or can be reproduced only on certain hardware configurations. If a
fatal error occurs, then the error log might contain the hardware details. If an error log is not
available, then document in the bug report the number and the type of processors in the
machine, the clock speed, and, where applicable and if known, some details on the features of
that processor. For example, in the case of Intel processors, it might be relevant that hyper-
threading is available.
• The kernel version: This can be obtained using the uname -a command.
• The glibc version: The rpm -q glibc command indicates the patch level of glibc.
• The thread library: There are two thread libraries for Linux, namely LinuxThreads and
NPTL. The LinuxThreads library is used on 2.4, and earlier kernels and has fixed stack and
floating stack variants. The Native POSIX Thread Library (NPTL) is used on the 2.6 kernel.
Some Linux releases (such as RHEL3) include backports of NPTL to the 2.4 kernel. Use the
command getconf GNU_LIBPTHREAD_VERSION to determine which thread library is used. If
the getconf command returns an error to say that the variable does not exist, then it is
likely that you are using an old kernel with the LinuxThreads library.
Java SE Version
Obtain the Java SE version string with the java -version command.
Multiple versions of Java SE may be installed on the same machine. Therefore, ensure that
you use the version of the java command used by the failing application. It is very likely to be
different from the default java command included in a user's PATH environment variable.
Command-Line Options
If the bug report does not include a fatal error log then, it is important to document the full
command line and all its options. This includes any options that specify heap settings, for
example, the -Xmx option, or any -XX options that specify HotSpot specific options.
If you can reproduce the issue at will, and you're able to read standard output (stdout) for the
JVM, then you can add the -XX:+PrintCommandLineFlags option to obtain the full list of
command-line options used by the application. This option will be active the next time the JVM
is restarted.
17-3
Chapter 17
Collect Data for a Bug Report
You can also run the jcmd command as follows to obtain the command-line options of a
running VM:
In addition, you can change the flags of a running JVM through jcmd. See the VM.set_flag
command.
Environment Variables
Sometimes problems arise due to environment variable settings. When creating the bug report,
indicate the values of the following Java environment variables (if set).
• JAVA_TOOL_OPTIONS
• _JAVA_OPTIONS
• CLASSPATH
• JAVA_COMPILER
• PATH
• USERNAME
Note:
You should obtain the values of environment variables from the context of the failing
application. In addition, one or more configuration files may set the values of these
environment variables for that failing application.
17-4
Chapter 17
Report a Bug
In general, provide all relevant logs, traces, and other output in the bug report or during the
support call.
Report a Bug
Once you have concluded that your issue was not already reported and collected data about it,
report it at Report a Bug or Request a Feature.
17-5
Chapter 17
Collect Core Dumps
Not all systems are configured to allow the creation of core files. The ulimit utility is used to
get or set the limitations on the system resources available to the current shell and its
descendants. Use the ulimit -c command to check or set the core file size limit. Ensure that
the limit is set to unlimited; otherwise, the core file could be truncated or not produced.
Note:
ulimit is a Bash shell built-in command; on a C shell, use the limit command.
Ensure that any scripts that are used to launch the VM or your application do not disable core
dump creation.
You can use the gcore command in the gdb (GNU debugger) interface to get a core image of a
running process. This utility accepts the pid of the process for which you want to force the core
dump.
To get the list of Java processes running on the machine, you can use any of the following
commands:
• jcmd
• ps -ef | grep java
• pgrep java
You can use the ShowMessageBoxOnError option to collect core dumps on Linux. Start a Java
process with the -XX:+ShowMessageBoxOnError command-line option. When a fatal error
occurs, the process prints a message to standard error and waits for a yes or no response from
standard input.
17-6
Chapter 17
Collect Core Dumps
• Java specific: If the process received SIGSEGV or SIGILL but did not produce a core file, it
is possible that the process handled it. For example, HotSpot VM uses the SIGSEGV signal
for legitimate purposes, such as throwing NullPointerException, deoptimization, and so
forth. The signal is unhandled by the Java VM only if the current instruction (PC) falls
outside the Java VM generated code. These are the only cases in which HotSpot dumps
the core.
• Java specific: The JNI Invocation API was used to create the VM. The standard Java
launcher was not used. The custom Java launcher program handled the signal by
consuming it and produced the log entry silently. This situation has occurred with certain
application servers and web servers. These Java VM embedding programs transparently
attempt to restart (fail over) the system after an abnormal termination. In this case, the fact
that a core dump is not produced is a feature and not a bug.
\\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AeDebug
The two values are named Debugger and Auto. The Auto value indicates if the debugger
specified in the value of the Debugger entry starts automatically when an application error
occurs.
• A value of 0 for Auto means that the system displays a message box notifying the user
when an application error occurs.
• A value of 1 for Auto means that the debugger starts automatically.
The value of Debugger is the debugger command that is to be used to debug program errors.
When a program error occurs, Windows examines the Auto value, and if the value is 0, then it
executes the command in the Debugger value. If the value for Debugger is a valid command,
then a message box is created with two buttons: OK and Cancel. If the user clicks OK, then
the program is terminated. If the user clicks Cancel, then the specified debugger is started. If
the value for the Auto entry is set to 1 and the value for the Debugger entry specifies the
command for a valid debugger, then the system automatically starts the debugger and does
not generate a message box.
The following are two ways to collect crash dump on Windows.
• Configure [Link]:
The Dr. Watson debugger is used to create crash dump files. By default, the Dr. Watson
debugger ([Link]) is installed in the Windows system folder (%SystemRoot%
\System32).
17-7
Chapter 17
Collect Core Dumps
To install Dr. Watson as the postmortem debugger, run the following command:
drwtsn32 -i
To configure the name and location of crash dump files, run drwtsn32 without any options.
In the Dr. Watson GUI window, ensure that the Create Crash Dump File check box is
selected and that the crash dump file path and log file path are configured in their
respective text fields.
Dr. Watson can be configured to create a full dump using the registry. The registry key is
shown in the following example.
Note:
If the application handles the exception, then the registry-configured debugger is
not invoked. In that case, it might be appropriate to use the -
XX:+ShowMessageBoxOnError command-line option to force the process to wait
for user intervention on fatal error conditions.
.dump /f [Link]
The windbg debugger is included in the Debugging Tools for Windows download.
An additional utility in this download is the [Link] utility, which can verify that a
memory dump file was created correctly.
Both [Link] and windbg require the pid of the process. The userdump -p command
lists the process and program for all processes. This is useful if you know that the
application is started with the [Link] launcher. However, if a custom launcher is used
(embedded VM), then it might be difficult to recognize the process. In that case, you can
use the jps command-line utility because it lists the PIDs of the Java processes only.
You can also use the -XX:+ShowMessageBoxOnError command-line option on Windows.
When a fatal error occurs, the process shows a message box and waits for a yes or no
response from the user.
17-8
Chapter 17
Collect Core Dumps
Before clicking Yes or No, you can use the [Link] utility to generate the Dr. Watson
dump for the Java process. This utility can also be used in cases when the process
appears to be hung.
17-9
Part VI
Appendices
This part contains the following topics.
• Fatal Error Log
Describes fatal error log contents and location
• Java 2D Properties
Describes properties that are useful in troubleshooting issues with Java 2D
• Environment Variables and System Properties
Describes environment variables and system properties that are useful when
troubleshooting issues with Java HotSpot Server VM
• Command-Line Options
Describes command-line options that are useful when diagnosing issues with Java
HotSpot Server VM
• Summary of Tools in This Release
Provides a summary of the tools available in the current and previous releases of the JDK.
A
Fatal Error Log
The fatal error log is created when a fatal error occurs. It contains information and the state
obtained at the time of the fatal error.
Note:
The format of this file can change slightly in update releases.
The substring %% in the file variable is converted to %, and the substring %p is converted to the
PID of the process.
In the following example, the error log file will be written to the directory /var/log/java and
will be named java_errorpid.log:
java -XX:ErrorFile=/var/log/java/java_error%[Link]
If the -XX:ErrorFile=file flag is not specified, then the default log file name is
hs_err_pid.log, where pid is the PID of the process.
In addition, if the -XX:ErrorFile=file flag is not specified, the system attempts to create
the file in the working directory of the process. In the event that the file cannot be created in the
working directory (insufficient space, permission problem, or other issue), the file is created in
the temporary directory for the operating system. On the Linux operating system, the
temporary directory is /tmp. On Windows, the temporary directory is specified by the value of
the TMP environment variable. If that environment variable is not defined, then the value of the
TEMP environment variable is used.
A-1
Appendix A
Description of Fatal Error Log
Note:
In some cases only a subset of this information is output to the error log. This can
happen when a fatal error is of such severity that the error handler is unable to
recover and report all the details.
Note:
The format of the fatal error log described here is based on Java SE 6. The format
might be different with other releases.
Header Format
The header section at the beginning of every fatal error log file contains a brief description of
the problem.
The header is also printed to standard output and may show up in the application's output log.
A-2
Appendix A
Header Format
The header includes a link to the HotSpot Virtual Machine Error Reporting Page, where the
user can submit a bug report.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f0f159f857d, pid=18240, tid=18245
#
# JRE version: Java(TM) SE Runtime Environment (9.0+167) (build 9-ea+167)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (9-ea+167, mixed mode, tiered,
compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C [[Link]+0x57d] Java_MyApp_readData+0x11
#
# Core dump will be written. Default location: /cores/core.18240)
#
# If you would like to submit a bug report, please visit:
# [Link]
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
The next line contains the VM version (client VM or server VM), an indication of whether the
application was run in mixed or interpreted mode, and an indication of whether class file
sharing was enabled, as shown in the following line.
# Java VM: Java HotSpot(TM) 64-Bit Server VM (9-ea+167, mixed mode, tiered,
compressed oops, g1 gc, linux-amd64)
The next line is the function frame that caused the crash, as shown in the following example.
A-3
Appendix A
Header Format
In this example, the "C" frame type indicates a native C frame. Table A-3 shows the possible
frame types.
Frame Description
Type
C Native C frame
j Interpreted Java frame
V VM frame
v VM-generated stub frame
J Other frame types, including compiled Java frames
Internal errors will cause the VM error handler to generate a similar error dump. However, the
header format is different. Examples of internal errors are guarantee() failure, assertion
failure, ShouldNotReachHere(), and so forth. The following example shows the header format
for an internal error.
#
# An unexpected error has been detected by HotSpot Virtual Machine:
#
# Internal Error (4F533F4C494E55583F491418160E43505000F5), pid=10226,
tid=16384
#
# Java VM: Java HotSpot(TM) Client VM (1.6.0-rc-b63 mixed mode)
In the above header, there is no signal name or signal number. Instead the second line now
contains Internal Error and a long hexadecimal string. This hexadecimal string encodes the
source module and line number where the error was detected. In general this "error string" is
useful only to engineers working on the HotSpot Virtual Machine.
The error string encodes a line number and therefore it changes with each code change and
release. A crash with a given error string in one release (for example, 1.6.0) might not
correspond to the same crash in an update release (for example, 1.6.0_01), even if the strings
match.
A-4
Appendix A
Thread Section Format
Note:
Do not assume that a workaround or solution that worked in one situation associated
with a given error string will work in another situation associated with that same error
string. Note the following facts:
• Errors with the same root cause might have different error strings.
• Errors with the same error string might have completely different root causes.
Therefore, the error string should not be used as the sole criterion when
troubleshooting bugs.
Thread Information
The first part of the thread section shows the thread that caused the fatal error, as shown in the
following example.
Current thread (0x00007f102c013000): JavaThread "main" [_thread_in_native,
id=18245, stack(0x00007f10345c0000,0x00007f10346c0000)]
The thread pointer is the pointer to the Java VM internal thread structure. It is generally of no
interest unless you are debugging a live Java VM or core file.
The following list shows possible thread types.
• JavaThread
• VMThread
• CompilerThread
• GCTaskThread
• WatcherThread
• ConcurrentMarkSweepThread
Table A-5 shows the important thread states.
A-5
Appendix A
Thread Section Format
Signal Information
The next information in the error log describes the unexpected signal that caused the VM to
terminate. On a Windows system the output appears as shown in the following example.
In the above example, the exception code is 0xc0000005 (ACCESS_VIOLATION), and the
exception occurred when the thread attempted to read address 0xd8ffecf1.
On the Linux operating system, the signal number (si_signo) and signal code (si_code) are
used to identify the exception, as follows:
Register Context
The next information in the error log shows the register context at the time of the fatal error.
The exact format of this output is processor-dependent. The following example shows output
for the Intel(R) Xeon(R) processor.
Registers:
RAX=0x0000000000000000, RBX=0x00007f0f17aff3b0, RCX=0x0000000000000001,
RDX=0x00007f1033880358
RSP=0x00007f10346be930, RBP=0x00007f10346be930, RSI=0x00007f10346be9a0,
RDI=0x00007f102c013218
R8 =0x00007f0f17aff3b0, R9 =0x0000000000000008, R10=0x00007f1011bb1de9,
R11=0x0000000101cfc5e0
R12=0x0000000000000000, R13=0x00007f0f17aff3b0, R14=0x00007f10346be9a8,
R15=0x00007f102c013000
RIP=0x00007f0f159f857d, EFLAGS=0x0000000000010283, CSGSFS=0x0000000000000033,
ERR=0x0000000000000004
A-6
Appendix A
Thread Section Format
The register values might be useful when combined with instructions, as described below.
Machine Instructions
After the register values, the following example shows the error log that contains the top of
stack followed by 32 bytes of instructions (opcodes) near the program counter (PC) when the
system crashed. These opcodes can be decoded with a disassembler to produce the
instructions around the location of the crash.
Note:
IA32 and AMD64 instructions are variable in length, and so it is not always possible
to reliably decode instructions before the crash PC.
Instructions: (pc=0x00007f0f159f857d)
0x00007f0f159f855d: 3d e6 08 20 00 ff e0 0f 1f 40 00 5d c3 90 90 55
0x00007f0f159f856d: 48 89 e5 48 89 7d f8 48 89 75 f0 b8 00 00 00 00
0x00007f0f159f857d: 8b 00 5d c3 90 90 90 90 90 90 90 90 90 90 90 90
0x00007f0f159f858d: 90 90 90 55 48 89 e5 53 48 83 ec 08 48 8b 05 88
Thread Stack
Where possible, the next output in the error log is the thread stack, as shown in the following
example. This includes the addresses of the base and the top of the stack, the current stack
pointer, and the amount of unused stack available to the thread. This is followed, where
possible, by the stack frames, and up to 100 frames are printed. For C/C++ frames, the library
name may also be printed. Note: In some fatal error conditions, the stack may be corrupt, and
this detail may not be available.
A-7
Appendix A
Process Section Format
j [Link]([Ljava/lang/String;)V+15
v ~StubRoutines::call_stub
Further Details
If the error occurred in the VM thread or in a compiler thread, then further details may be seen
from the following example. For example, in the case of the VM thread, the VM operation is
printed if the VM thread is executing a VM operation at the time of the fatal error. In the
following output example, the compiler thread caused the fatal error. The task is a compiler
task, and the HotSpot Client VM is the compiling method [Link].
Current CompileTask:
HotSpot Client Compiler:754 b
[Link](IJ)J (42 bytes)
For the HotSpot Server VM, the output for the compiler task is slightly different but will also
include the full class name and method.
Thread List
The thread list includes the threads that the VM is aware of, as shown in the following
example.
A-8
Appendix A
Process Section Format
This includes all Java threads and some VM internal threads, but does not include any native
threads created by the user application that have not attached to the VM, as shown in the
following example.
Other Threads:
0x00007f102c43f000 VMThread "VM Thread" [stack:
0x00007f0f175ff000,0x00007f0f176ff000] [id=18296]
0x00007f102c54b000 WatcherThread [stack:
0x00007f0f15bfb000,0x00007f0f15cfb000] [id=18338]
The thread type and thread state are described in Thread Section Format.
VM State
The next information is the VM state, which indicates the overall state of the virtual machine.
Table A-7 describes the general states.
A-9
Appendix A
Process Section Format
Heap Summary
The next information is a summary of the heap, as shown in the following example. The output
depends on the garbage collection (GC) configuration. In this example, the serial collector is
used, class data sharing is disabled, and the tenured generation is empty. This probably
indicates that the fatal error occurred early or during startup, and a GC has not yet promoted
any objects into the tenured generation.
Heap
def new generation total 576K, used 161K [0x46570000, 0x46610000,
0x46a50000)
eden space 512K, 31% used [0x46570000, 0x46598768, 0x465f0000)
from space 64K, 0% used [0x465f0000, 0x465f0000, 0x46600000)
to space 64K, 0% used [0x46600000, 0x46600000, 0x46610000)
tenured generation total 1408K, used 0K [0x46a50000, 0x46bb0000,
0x4a570000)
the space 1408K, 0% used [0x46a50000, 0x46a50000, 0x46a50200, 0x46bb0000)
compacting perm gen total 8192K, used 1319K [0x4a570000, 0x4ad70000,
0x4e570000)
the space 8192K, 16% used [0x4a570000, 0x4a6b9d48, 0x4a6b9e00, 0x4ad70000)
No shared spaces configured.
Memory Map
The next information in the log is a list of virtual memory regions at the time of the crash. This
list can be long if the application is large. The memory map can be very useful when
debugging some crashes, because it can tell you which libraries are actually being used, their
location in memory, as well as the location of the heap, stack, and guard pages.
The format of the memory map is operating system-specific. On the Linux system, the process
memory map (/proc/pid/maps) is printed. On the Windows system, the base and end
addresses of each library are printed. The following example shows the output generated on
Linux/x86.
A-10
Appendix A
Process Section Format
Note:
Most of the lines were omitted from the example for the sake of brevity.
Dynamic libraries:
00400000-00401000 r-xp 00000000 00:47 1374716350 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/bin/java
00601000-00602000 rw-p 00001000 00:47 1374716350 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/bin/java
016c6000-016e7000 rw-p 00000000 00:00 0
[heap]
82000000-102000000 rw-p 00000000 00:00 0
102000000-800000000 ---p 00000000 00:00 0
40014000-40015000 r--p 00000000 00:00 0
Lines omitted.
7f0f159f8000-7f0f159f9000 r-xp 00000000 08:11 116808980 /
export/users/dh198349/tests/hs-err/[Link]
7f0f159f9000-7f0f15bf8000 ---p 00001000 08:11 116808980 /
export/users/dh198349/tests/hs-err/[Link]
7f0f15bf8000-7f0f15bf9000 r--p 00000000 08:11 116808980 /
export/users/dh198349/tests/hs-err/[Link]
7f0f15bf9000-7f0f15bfa000 rw-p 00001000 08:11 116808980 /
export/users/dh198349/tests/hs-err/[Link]
Lines omitted.
7f0f15dfc000-7f0f15e00000 ---p 00000000 00:00 0
7f0f15e00000-7f0f15efd000 rw-p 00000000 00:00 0
7f0f15efd000-7f0f15f13000 r-xp 00000000 00:47 1374714565 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/lib/[Link]
7f0f15f13000-7f0f16113000 ---p 00016000 00:47 1374714565 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/lib/[Link]
7f0f16113000-7f0f16114000 rw-p 00016000 00:47 1374714565 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/lib/[Link]
7f0f16114000-7f0f16124000 r-xp 00000000 00:47 1374714619 /
export/java_re/jdk/9/ea/167/binaries/linux-x64/lib/[Link]
Lines omitted.
7f0f17032000-7f0f17036000 ---p 00000000 00:00 0
7f0f17036000-7f0f17133000 rw-p 00000000 00:00 0
7f0f17133000-7f0f173fc000 r--p 00000000 08:02
2102853 /usr/lib/locale/locale-archive
7f0f173fc000-7f0f17400000 ---p 00000000 00:00 0
Lines omitted.
A-11
Appendix A
Process Section Format
The example shows the memory map output and each library has two virtual memory regions:
one for code and one for data. The permission for the code segment is marked with r-xp
(readable, executable, private), and the permission for the data segment is rw-p (readable,
writable, private).
The Java heap is already included in the heap summary earlier in the output, but it can be
useful to verify that the actual memory regions reserved for the heap match the values in the
heap summary and that the attributes are set to rwxp.
Thread stacks usually show up in the memory map as two back-to-back regions, one with
permission ---p (guard page) and one with permission rwxp (actual stack space). In addition, it
is useful to know the guard page size or stack size. For example, in this memory map, the
stack is located from 4127b000 to 412fb000.
On a Windows system, the memory map output is the load and end address of each loaded
module, as shown in the following example.
Dynamic libraries:
0x00400000 - 0x0040c000 c:\jdk6\bin\[Link]
0x77f50000 - 0x77ff7000 C:\WINDOWS\System32\[Link]
0x77e60000 - 0x77f46000 C:\WINDOWS\system32\[Link]
0x77dd0000 - 0x77e5d000 C:\WINDOWS\system32\[Link]
0x78000000 - 0x78087000 C:\WINDOWS\system32\[Link]
0x77c10000 - 0x77c63000 C:\WINDOWS\system32\[Link]
0x08000000 - 0x08183000 c:\jdk6\jre\bin\client\[Link]
0x77d40000 - 0x77dcc000 C:\WINDOWS\system32\[Link]
0x7e090000 - 0x7e0d1000 C:\WINDOWS\system32\[Link]
0x76b40000 - 0x76b6c000 C:\WINDOWS\System32\[Link]
0x6d2f0000 - 0x6d2f8000 c:\jdk6\jre\bin\[Link]
0x76bf0000 - 0x76bfb000 C:\WINDOWS\System32\[Link]
0x6d680000 - 0x6d68c000 c:\jdk6\jre\bin\[Link]
0x6d370000 - 0x6d38d000 c:\jdk6\jre\bin\[Link]
0x6d6a0000 - 0x6d6af000 c:\jdk6\jre\bin\[Link]
0x10000000 - 0x10032000 C:\bugs\crash2\[Link]
A-12
Appendix A
Process Section Format
VM Arguments:
jvm_args:
java_command: MyApp
java_class_path (initial): .
Launcher Type: SUN_STANDARD
Logging:
Log output configuration:
#0: stdout all=warning uptime,level,tags
#1: stderr all=off uptime,level,tags
Environment Variables:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
SHELL=/bin/bash
DISPLAY=localhost:10.0
ARCH=i386
Note:
The list of environment variables is not the full list but rather a subset of the
environment variables that are applicable to the Java VM.
Signal Handlers
On the Linux operating system, the next information in the error log is the list of signal
handlers, as shown in the following example.
Signal Handlers:
SIGSEGV: [[Link]+0xd48840], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGBUS: [[Link]+0xd48840], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGFPE: [[Link]+0xd48840], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGPIPE: [[Link]+0xb60080], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGXFSZ: [[Link]+0xb60080], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGILL: [[Link]+0xd48840], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGUSR2: [[Link]+0xb5ff40], sa_mask[0]=00000000000000000000000000000000,
sa_flags=SA_RESTART|SA_SIGINFO
SIGHUP: [[Link]+0xb60150], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGINT: [[Link]+0xb60150], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
SIGTERM: [[Link]+0xb60150], sa_mask[0]=11111111011111111101111111111110,
A-13
Appendix A
System Section Format
sa_flags=SA_RESTART|SA_SIGINFO
SIGQUIT: [[Link]+0xb60150], sa_mask[0]=11111111011111111101111111111110,
sa_flags=SA_RESTART|SA_SIGINFO
--------------- S Y S T E M ---------------
OS:DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04 LTS"
uname:Linux 3.2.0-24-generic #39-Ubuntu SMP Mon May 21 [Link] UTC 2012
x86_64
libc:glibc 2.15 NPTL 2.15
rlimit: STACK 8192k, CORE infinity, NPROC 1160369, NOFILE 4096, AS infinity
load average:0.46 0.33 0.27
/proc/meminfo:
MemTotal: 148545440 kB
MemFree: 1020964 kB
Buffers: 29600728 kB
Cached: 86607768 kB
SwapCached: 16112 kB
Active: 52272944 kB
Inactive: 64862992 kB
Active(anon): 314080 kB
Inactive(anon): 616296 kB
Active(file): 51958864 kB
Inactive(file): 64246696 kB
Unevictable: 16 kB
Mlocked: 16 kB
SwapTotal: 1051644 kB
SwapFree: 976092 kB
Dirty: 40 kB
Writeback: 0 kB
AnonPages: 912404 kB
Mapped: 95804 kB
Shmem: 2936 kB
Slab: 28625980 kB
SReclaimable: 28337400 kB
SUnreclaim: 288580 kB
KernelStack: 6040 kB
PageTables: 42524 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 75324364 kB
Committed_AS: 6172612 kB
A-14
Appendix A
System Section Format
VmallocTotal: 34359738367 kB
VmallocUsed: 681668 kB
VmallocChunk: 34282379392 kB
HardwareCorrupted: 0 kB
AnonHugePages: 0 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
DirectMap4k: 171520 kB
DirectMap2M: 8208384 kB
DirectMap1G: 142606336 kB
CPU:total 24 (initial active 24) (6 cores per cpu, 2 threads per core) family
6 model 44 stepping 2, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1,
sse4.2, popcnt, aes, clmul, ht, tsc, tscinvbit, tscinv
CPU Model and flags from /proc/cpuinfo:
model name : Intel(R) Xeon(R) CPU X5675 @ 3.07GHz
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov
pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb
rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology
nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2
ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 popcnt aes lahf_lm ida arat epb
dts tpr_shadow vnmi flexpriority ept vpid
vm_info: Java HotSpot(TM) 64-Bit Server VM (9-ea+167) for linux-amd64 JRE (9-
ea+167), built on Apr 27 2017 [Link] by "javare" with gcc 4.9.2
On the Linux, the operating system, information is in the file /etc/*release. This file
describes the kind of system the application is running on, and in some cases, the information
string might include the patch level. Some system upgrades are not reflected in the /etc/
*release file. This is especially true on the Linux system, where the user can rebuild any part
of the system.
On the Linux system, the uname system call is used to get the kernel name. The libc version
and the thread library type are also printed, as shown in the following example.
On Linux, there are three possible thread types, namely linuxthreads (fixed stack),
linuxthreads (floating stack), and NPTL. They are normally installed in /lib, /lib/i686,
and /lib/tls.
It is useful to know the thread type. For example, if the crash appears to be related to pthread,
then you might be able to work around the issue by selecting a different pthread library. A
different pthread library (and libc) can be selected by setting LD_LIBRARY_PATH or
LD_ASSUME_KERNEL.
A-15
Appendix A
System Section Format
The glibc version usually does not include the patch level. The command rpm -q glibc might
provide more detailed version information.
On the Linux operating system, the next information is the rlimit information.
Note:
The default stack size of the VM is usually smaller than the system limit, as shown in
the following examples:
rlimit: STACK 8192k, CORE infinity, NPROC 1160369, NOFILE 4096, AS infinity
load average:0.04 0.05 0.02
rlimit: STACK 8192k, CORE 0k, NPROC 4092, NOFILE 1024, AS infinity
load average:0.04 0.05 0.02
The next information specifies the CPU architecture and capabilities identified by the VM at
startup, as shown in the following example.
CPU:total 24 (initial active 24) (6 cores per cpu, 2 threads per core) family
6 model 44 stepping 2, cmov, cx8, fxsr, mmx,sse, sse2, sse3, ssse3, sse4.1,
sse4.2, popcnt, aes, clmul, ht, tsc, tscinvbit, tscinv
A-16
Appendix A
System Section Format
AMD64/EM64T Description
Feature
amd64 AMD Opteron, Athlon64, and so forth.
em64t Intel EM64T processor.
A-17
Appendix A
System Section Format
AMD64/EM64T Description
Feature
3dnow Supports 3DNow extension.
ht Supports Hyper-Threading Technology.
The next information in the error log is memory information, as shown in the following example.
Some systems require swap space to be at lease twice the size of real physical memory,
whereas other systems do not have any requirements. As a general rule, if both physical
memory and swap space are almost full, then there is good reason to suspect that the crash
was due to insufficient memory.
On Linux system, the kernel may convert most of unused physical memory to file cache. When
there is a need for more memory, the Linux kernel will give the cache memory back to the
application. This is handled transparently by the kernel, but it means that the amount of unused
physical memory reported by the fatal error handler could be close to zero when there is still
sufficient physical memory available.
The final information in the SYSTEM section of the error log is vm_info, which is a version
string embedded in [Link]/[Link]. Every Java VM has its own unique vm_info string.
If you are in doubt about whether the fatal error log was generated by a particular Java VM,
check the version string.
A-18
B
Java 2D Properties
This appendix presents properties that can be useful in troubleshooting Java 2D.
This appendix contains the following sections:
• Properties on Linux
• Properties on Windows
• Properties on macOS
Properties on Linux
Table B-1 describes the default values of some useful properties on the Linux platform.
B-1
Appendix B
Properties on Windows
Properties on Windows
The following list describes some useful properties on Windows platforms.
• The DirectDraw/GDI pipeline is the default pipeline for Windows. Change this default as
follows:
– -[Link]=true — Disable the use of the DirectDraw pipeline. GDI will
be used instead.
– -[Link]=false — Enable the use of the DirectDraw pipeline.
– -Dsun.java2d.d3d=false — Disable the use of the Direct3D pipeline.
– J2D_D3D=false — Disable the use of the Direct3D pipeline.
– -Dsun.java2d.d3d=true — Enable the use of the Direct3D pipeline.
– J2D_D3D=true — Enable the use of the Direct3D pipeline.
• Control the use of the built-in surface punting mechanism as follows:
– -[Link]=true — Keep volatile images in VRAM.
• Control the use of DirectDraw blit operations as follows:
– -[Link]=false — Disable the use of DirectDraw blit operations. GDI
blits will be used instead.
Properties on macOS
The following table describes some useful Java 2D properties on macOS.
B-2
C
Environment Variables and System Properties
This appendix describes environment variables and system properties that can be useful for
troubleshooting problems with the Java HotSpot VM.
Submit a Bug Report contains information on collecting environment variables in Environment
Variables.
This appendix contains the following sections:
• The JAVA_TOOL_OPTIONS Environment Variable
• The [Link] System Property
Note:
In some cases, this option is disabled for security reasons.
This environment variable allows you to specify the initialization of tools, specifically the
launching of native or Java programming language agents using the -agentlib or -javaagent
options.
This variable can also be used to augment the command line with other options for diagnostic
purposes. For example, you can supply the -XX:OnError option to specify a script or command
to be executed when a fatal error occurs.
Because this environment variable is examined at the time, that the JNI_CreateJavaVM function
is called, it cannot be used to augment the command line with options that would normally be
handled by the launcher, for example, VM selection using the -client option or the -server
option.
C-1
Appendix C
The [Link] System Property
To learn more about the [Link] system property, see Troubleshooting Security
in the Java Platform, Standard Edition Security Developer's Guide.
C-2
D
Command-Line Options
This appendix describes some command-line options that can be useful when diagnosing
problems with the Java HotSpot VM.
This appendix contains the following sections:
• Java HotSpot VM Command-Line Options
• Other Command-Line Options
You can dynamically set, unset, or change the value of certain Java VM flags for a specified
Java process using the jinfo -flag command. See The jinfo Utility and the JConsole utility.
For a complete list of these flags, use the MBeans tab of the JConsole utility. See the list of
values for the DiagnosticOptions attribute of the HotSpotDiagnostic MBean, which is in the
[Link] domain. The following are the flags:
• HeapDumpOnOutOfMemoryError
• HeapDumpPath
• PrintGC
• PrintGCDetails
• PrintGCTimeStamps
• PrintClassHistogram
• PrintConcurrentLocks
You can also specify this option at runtime with the MBeans tab in the JConsole utility.
The following example shows the result of running out of memory with this flag set.
D-1
Appendix D
Java HotSpot VM Command-Line Options
The ConsumeHeap fills the Java heap and runs out of memory. When a
[Link] is thrown, a heap dump file is created. In this case the file is 507
MB and is created with the name java_pid2262.hprof in the current directory.
By default, the heap dump is created in a file called java_pidpid.hprof in the working
directory of the VM, as in the example above. You can specify an alternative file name or
directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps
will cause the heap dump to be generated in the /disk2/dumps directory.
Note:
The example assumes that the path to the [Link] utility is defined in the
PATH variable.
To know more about creating crash dumps on Windows, see Collect Crash Dumps on
Windows.
D-2
Appendix D
Java HotSpot VM Command-Line Options
==============================================================================
Unexpected Error
------------------------------------------------------------------------------
SIGSEGV (0xb) at pc=0x2000000001164db1, pid=10791, tid=1026
In this case, a SIGSEGV error occurred, and the user is prompted to specify whether the gdb
debugger is to be launched to attach to the process. If the user enters y or yes, thengdb will be
launched (assuming it is set in the PATH variable).
On Windows a message box is displayed. If the user clicks Yes, the VM will attempt to start the
default debugger. This debugger is configured by a registry setting which is described in
Collect Crash Dumps on Windows. If Microsoft Visual Studio is installed, the default debugger
is typically configured to be [Link].
In the above example, the output includes the PID (pid=10791) and also the thread ID
(tid=1026). If the debugger is launched, one of the initial steps in the debugger might be to
select the thread and get its stack trace.
When the process is waiting for a response, it is possible to use other tools to get a crash
dump or query the state of the process.
On Windows, a Dr. Watson crash dump can be obtained using the userdump or windbg
programs. The windbg utility is included in Microsoft's Debugging Tools for Windows and is
described in Collect Crash Dumps on Windows. In windbg, select the Attach to a Process
menu option, which displays the list of processes and prompts for the PID. The HotSpot VM
displays a message box, which includes the PID. After you selected the PID, the .dump /f
command can be used to force a crash dump. Figure D-1 is an example crash dump created in
a file named [Link].
D-3
Appendix D
Java HotSpot VM Command-Line Options
• -XX:OnOutOfMemoryError=string
This option can be used to specify a command or script to execute when a
[Link] is thrown.
• -XX:ErrorFile=filename
This option can be used to specify a location for the fatal error log file. See Location of
Fatal Error Log.
• -xx:HeapDumpPath=path
This option can be used to specify a location for the heap dump. See The -
XX:HeapDumpOnOutOfMemoryError Option.
• -XX:MaxPermSize=size
This option can be used to specify the size of the permanent generation memory. See The
[Link] Error.
• -XX:+PrintCommandLineFlags
D-4
Appendix D
Other Command-Line Options
This option can be used to print all the VM command-line flags. See Collect Data for a Bug
Report.
• -XX:+PrintConcurrentLocks
This option can be used to cause the Control+Break handler to print a list of concurrent
locks owned by each thread.
• -XX:+PrintClassHistogram
This option can be used to cause the Control+Break handler to print a heap histogram.
• -XX:+PrintGCDetails and-XX:+PrintGCTimeStamps
These options can be used to print detailed information about garbage collection. See The
-verbose:gc Option.
• -XX:+UseConcMarkSweepGC , -XX:+UseSerialGC and -XX:+UseParallelGC
These options can be used to specify the garbage collection policy to be used. See
Working Around Crashes During Garbage Collection.
The -Xcheck:jni option causes the VM to do additional validation of the use of JNI
functions. This includes argument validation and other usage constraints as described below.
Note:
The option is not guaranteed to find all invalid arguments or diagnose logic bugs in
the application code, but it can help diagnose a large number of such problems.
When a significant usage error is detected, the VM prints a message to the application console
or to standard output, prints the stack trace of the offending thread, and stops the VM.
The following example shows a null value was incorrectly passed to a JNI function that does
not allow a null value.
D-5
Appendix D
Other Command-Line Options
The following example shows an incorrect argument that was provided to a JNI function that
expects a jfieldID argument.
FATAL ERROR in native method: Instance field not found in JNI get/set
field operations
at [Link](Native Method)
at [Link]([Link])
- locked <0xf082f290> (a [Link])
at [Link]([Link])
at [Link].<init>([Link])
at jvm003a.<init>([Link])
at jvm003a.<init>([Link])
at [Link]([Link])
at [Link]([Link])
The following checks are considered indicative of significant problems with the native code:
• The thread doing the call is not attached to the JVM
• The thread doing the call is using the JNIEnv belonging to another thread
• A parameter validation check fails:
– A jfieldID, or jmethodID, is detected as being invalid. For example:
* Of the wrong type
* Associated with the wrong class
– A parameter of the wrong type is detected
– An invalid parameter value is detected. For example:
* NULL where not permitted
* An out-of-bounds array index, or frame capacity
* A non-UTF-8 string
* An invalid JNI reference
* An attempt to use a ReleaseXXX function on a parameter not produced by the
corresponding GetXXX function
The following checks only result in warnings being printed:
• A JNI call was made without checking for a pending exception from a previous JNI call,
and the current call is not safe when an exception may be pending
• The number of JNI local references existing when a JNI function terminates exceeds the
number guaranteed to be available. See the EnsureLocalcapacity function
D-6
Appendix D
Other Command-Line Options
A JNI critical region is created when native code uses the JNI functions
GetPrimitiveArrayCritical or GetStringCritical to obtain a reference to an array or string
in the Java heap. The reference is held until the native code calls the corresponding release
function. The code between the get and release is called a JNI critical section, and during that
time, the HotSpot VM cannot bring the VM to a state that allows garbage collection to occur.
The general recommendation is not to use other JNI functions within a JNI critical section, and
in particular any JNI function that could potentially cause a deadlock. The warning printed
above by the -Xcheck:jni option is thus an indication of a potential issue; it does not always
indicate an application bug.
D-7
E
Summary of Tools in This Release
This appendix provides a summary of tools available in the current release of the JDK.
All of the JDK troubleshooting tools that are described in this document are available on Linux.
The following JDK troubleshooting tools are also available on Windows:
• Flight Recorder
• jcmd
• JConsole
• Java Virtual Machine
• jdb
• jinfo
• jmap
• jps
• jrunscript
• jstack
• jstat
• jstatd
• visualgc
E-1