Chapter 11. Memory Management

Java has automatic memory management, which is also known as garbage collection (GC). GC’s principal tasks are allocating memory, maintaining referenced objects in memory, and recovering memory from objects that no longer have references to them.

Garbage Collectors

Since the J2SE 5.0 release, the Java HotSpot Virtual Machine performs self-tuning. This process includes the attempted best-fit GC and related settings at startup, based on platform information, as well as ongoing GC tuning.

Although the initial settings and runtime tuning for GC are generally successful, there are times when you may wish to change or tune your GC based on the following goals:

Maximum pause time goal

The maximum pause time goal is the desired time that the GC pauses the application to recover memory.

Throughput goal

The throughput goal is the desired application time, or the time spent outside of GC.

The following sections provide an overview of various garbage collectors, their main focus, and situations in which they should be used. “Command-Line Options” explains how to acquire information for manually selecting the GC.

Serial Collector

The serial collector is performed via a single thread on a single CPU. When this GC thread is run, the execution of the application will pause until the collection is complete.

This collection is best used when your application has a small data set, up to approximately 100 MB, and does not have a requirement for low pause times.

Parallel Collector

The parallel collector, also known as the throughput collector, can be performed with multiple threads across several CPUs. Using these multiple threads significantly speeds up GC.

This collector is best used when there are no pause time constraints and application performance is the most important aspect of your program.

Parallel Compacting Collector

The parallel compacting collector is similar to the parallel collector, except for refined algorithms that reduce collection pause times.

This collector is best used for applications that do have pause time constraints.

Tip

The parallel compacting collector is available beginning with J2SE 5.0 update 6.

Concurrent Mark-Sweep Collector

The Concurrent Mark-Sweep (CMS), also known as the low-latency collector, implements algorithms to handle large collections that might warrant long pauses.

This collector is best used when response times take precedence over throughput times and GC pauses.

Garbage-First (G1) Collector

The Garbage-First collector, also known as the G1 collector, is used for multiprocessor machines with large memories. This server-style GC meets pause time goals with high probability, while achieving high throughput. Whole-heap operations (e.g., global marking) are performed concurrently with the application threads, which prevents interruptions proportional to the heap or live-data size.

Tip

Java SE 9 has made G1 the default garbage collector on 32-bit and 64-bit server configurations. G1 has been available since Java SE 7 update 4

Memory Management Tools

Although tuning your GC may prove to be successful, it is important to note that the GCs do not provide guarantees, only goals; however, any improvement gained on one platform may be undone on another. It is best to find the source of the problem with memory management tools, including profilers.

Table 11-1 lists such tools. All are command-line applications, except Heap/CPU Profiling Tool (HPROF). HPROF is dynamically loaded from a command-line option.

Table 11-1. JDK memory management tools
Resource Description

jvisualvm

Troubleshooting tool packaged in Java 8 but external to 9

jconsole

Java Management Extensions (JMX)-compliant monitoring tool

jinfo

Configuration information tool

jstat

JVM statistics monitoring tool

jstatd

jstat with remote tools attachment

jmc

Profiling, monitoring, and diagnostics tools

jmap

Memory map tool

jstack

Stack trace tool

jcmd

Diagnostic command request tool

jdb

Java debugger tool

jps

Instrumented JVMs listing tool

Tip

Consider exploring Oracle Java SE Advanced, which includes Java Mission Control (i.e., jmc) and Java Flight Recorder. These are enterprise-grade, production-savvy diagnostics and monitoring tools. Java Flight Recorder requires a commercial license for use in production.

Command-Line Options

The following GC-related command-line options can be passed into the Java interpreter to interface with the functionality of the Java HotSpot Virtual Machine:

-XX:+PrintGC or -verbose:gc

Prints out general information about the heap and garbage collection at each collection. GC logging uses the unified JVM logging framework as of Java 9.

-XX:+PrintCommandLineFlags -version

Prints out heap settings, applied -XX values, and version information.

-XX:+PrintGCDetails

Prints out detailed information about the heap and garbage collection during each collection.

-XX:+PrintGCTimeStamps

Adds timestamps to the output from PrintGC or Print-GCDetails.

-XX:+UseSerialGC

Enables the serial collector.

-XX:+UseParallelGC

Enables the parallel collector for scavenges.

-XX:+UseParallelOldGC

Enables the parallel collector for full collectors.

-XX:+UseParNewGC

Enables the parallel young generation collector. Can be used with the concurrent low pause collector. Removed in Java 9.

-XX:+UseConcMarkSweepGC

Enables the concurrent low pause CMS collector. Can be used with the parallel young generation collector. Removed in Java 9.

-XX:+UseG1GC

Enables the Garbage-First collector.

-XX:+DisableExplicitGC

Disables the explicit GC (System.gc()) methods.

-XX:ParallelGCThreads=[threads]

Defines the number of GC threads. The default correlates to the number of CPUs. This option applies to the CMS and parallel collectors.

-XX:MaxGCPauseMillis=[milliseconds]

Provides a hint to the GC for the desired maximum pause time goal in milliseconds. This option applies to the parallel collectors.

-XX:+GCTimeRatio=[__value__]

Provides a hint to the GC for the desired ratio of GC time to application time (1 / (1 + [value])) for the desired throughput goal. The default value is 99. This means that the application will run 99% of the time, and therefore the GC will run 1% of the time. This option applies to the parallel collectors.

-XX:+CMSIncrementalMode

Enables incremental mode for the CMS collector only. Used for machines with one or two processors. Removed in Java 9.

-XX:+CMSIncrementalPacing

Enables automatic packing for the CMS collector only.

-XX:MinHeapFreeRatio=[percent]

Sets the minimum target percent for the proportion of free space to total heap size. The default percent is 40.

-XX:MaxHeapFreeRatio=[percent]

Sets the maximum target percent for the proportion of free space to total heap size. The default percent is 70.

-Xms[bytes]

Overrides the minimum heap size in bytes. Default: 1/64 of the system’s physical memory up to 1 GB. Initial heap size is 4 MB for machines that are not server-class.

-Xmx[bytes]

Overrides the maximum heap size in bytes. Default: Smaller than 1/4 physical memory or 1 GB. Maximum heap size is 64 MB for machines that are not server-class.

-Xmn[bytes]

The size of the heap for the young generation.

-XX:OnError=[command_line_tool [__options__]]

Used to specify user-supplied scripts or commands when a fatal error occurs.

-XX+AggressiveOpts

Enables performance optimizations that are expected to be on by default in future releases.

For a more complete list of options, visit Java HotSpot VM Options. Java 9 validates command-line flags to avoid crashes.

Tip

Byte values include [k|K] for kilobytes, [m|M] for megabytes, and [g|G] for gigabytes.

Note that –XX options are not guaranteed to be stable. They are not part of the Java Language Specification (JLS) and are unlikely to be available in exact form and function from other third-party JVMs, if at all.

Resizing the JVM Heap

The heap is an area in memory that stores all objects created by executing a Java program. You should resize the heap only if it needs to be sized larger than the default heap size. If you are having performance problems or seeing the Permanent Generation (PermGen) error message java.lang.OutOfMemoryError, you may be running out of heap space.

Metaspace

Native memory is used for the representation of class metadata, creating a memory space called Metaspace. Metaspace is the sucessor to the PermGen model. Because of this, the JDK 8 HotSpot JVM will no longer see any PermGen OutOfMemoryError occurring. JVisualVM, prior to Java 9, provides analysis support to the Metaspace if any memory leaks should occur. JVisualVM is now VisualVM maintained on GitHub.

Interfacing with the GC

Interfacing with the garbage collector can be done through explicit invocation or via overriding the finalize method.

Explicit Garbage Collection

The garbage collector can be explicitly requested to be invoked with System.gc() or Runtime.getRuntime().gc(). However, explicit invocation of the GC should generally be avoided because it could force full collections (when a minor collection may suffice), thereby unnecessarily increasing the pause times. The request for System.gc() is not always fulfilled as the JVM can and does ignore it at times.

Finalization

Every object has a finalize() method inherited from class Object. The garbage collector, prior to destroying the object, can invoke this method, but this invocation is not guaranteed. The default implementation of the finalize() method does nothing, and although it is not recommended, the method can be overridden:

public class TempClass extends SuperClass {
  ...
  // Performed when garbage collection occurs
  protected void finalize() throws Throwable {
    try {
      /* Desired functionality goes here */
    } finally {
      // Optionally, you can call the
      // finalize method of the superclass
      super.finalize(); // From SuperClass
    }
  }
}

The following example destroys an object:

public class MainClass {
  public static void main(String[] args) {
    TempClass t = new TempClass();
    // Object has references removed
    t = null;
    // GC made available
    System.gc();
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.91