Skip to content

Commit

Permalink
Merge pull request #1432 from madeline-underwood/JavaGC
Browse files Browse the repository at this point in the history
Java GC_approved by Andy Pickard
  • Loading branch information
pareenaverma authored Dec 13, 2024
2 parents ef0c85d + 872cb4c commit 7708c98
Show file tree
Hide file tree
Showing 8 changed files with 165 additions and 117 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
---
title: Example Application
weight: 4
weight: 5

### FIXED, DO NOT MODIFY
layout: learningpathall
---

## Example Application.
## Example Application

Using a file editor of your choice, copy the Java snippet below into a file named `HeapUsageExample.java`. This code example allocates 1 million string objects to fill up the heap. You can use this example to easily observe the effects of different GC tuning parameters.
Using a file editor of your choice, copy the Java snippet below into a file named `HeapUsageExample.java`.

This code example allocates 1 million string objects to fill up the heap. You can use this example to easily observe the effects of different GC tuning parameters.

```java
public class HeapUsageExample {
Expand All @@ -32,9 +34,13 @@ public class HeapUsageExample {
}
```

### Enable GC logging
### Enable Garbage Collector logging

To observe what the Garbage Collector is doing, one option is to enabling logging while the JVM is running.

To enable this, you need to pass in some command-line arguments. The `gc` option logs the GC information. The `filecount` option creates a rolling log to prevent uncontrolled growth of logs with the drawback that historical logs might be rewritten and lost.

To observe what the GC is doing, one option is to enabling logging while the JVM is running. To enable this, you need to pass in some command-line arguments. The `gc` option logs the GC information. The `filecount` option creates a rolling log to prevent uncontrolled growth of logs with the drawback that historical logs may be rewritten and lost. Run the following command to enable logging with JDK 11 and higher:
Run the following command to enable logging with JDK 11 and higher:

```bash
java -Xms512m -Xmx1024m -XX:+UseSerialGC -Xlog:gc:file=gc.log:tags,uptime,time,level:filecount=10,filesize=16m HeapUsageExample.java
Expand All @@ -46,7 +52,7 @@ If you are using JDK8, use the following command instead:
java -Xms512m -Xmx1024m -XX:+UseSerialGC -Xloggc:gc.log -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation HeapUsageExample.java
```

The `-Xms512m` and `-Xmx1024` options create a minimum and maximum heap size of 512 MiB and 1GiB respectively. This is simply to avoid waiting too long to see activity within the GC. Additionally, you will force the JVM to use the serial garbage collector with the `-XX:+UseSerialGC` flag.
The `-Xms512m` and `-Xmx1024` options create a minimum and maximum heap size of 512 MiB and 1GiB respectively. This is to avoid waiting too long to see activity within the GC. Additionally, you can force the JVM to use the serial garbage collector with the `-XX:+UseSerialGC` flag.

You will now see a log file, named `gc.log` created within the same directory.

Expand All @@ -58,17 +64,19 @@ Open `gc.log` and the contents should look similar to:
[2024-11-08T15:04:54.350+0000][0.759s][info][gc] GC(3) Pause Young (Allocation Failure) 139M->3M(494M) 3.699ms
```

These logs provide insights into the frequency, duration, and impact of Young garbage collection events. The results may vary depending on your system.
These logs provide insights into the frequency, duration, and impact of Young garbage collection events. The results can vary depending on your system.

- Frequency: ~ every 46 ms
- Pause duration: ~ 3.6 ms
- Reduction size: ~ 139 MB (or 3M objects)

This logging method can be quite verbose. Also, this method isn't suitable for a running process which makes debugging a live running application slightly more challenging.
This logging method can be quite verbose, and makes it challenging to debug a live running application.

### Use jstat to observe real-time GC statistics

Using a file editor of your choice, copy the java code below into a file named `WhileLoopExample.java`. This java code snippet is a long-running example that prints out a random integer and double precision floating point number 4 times a second.
Using a file editor of your choice, copy the java code below into a file named `WhileLoopExample.java`.

This java code snippet is a long-running example that prints out a random integer and double precision floating point number four times a second:

```java
import java.util.Random;
Expand All @@ -91,7 +99,7 @@ public class GenerateRandom {
// Print random double
System.out.println("Random Doubles: " + rand_dub1);

// Sleep for 1 second (1000 milliseconds)
// Sleep for 1/4 second (250 milliseconds)
try {
Thread.sleep(250);
} catch (InterruptedException e) {
Expand All @@ -107,13 +115,15 @@ Start the Java program with the command below. This will use the default paramet
```bash
java WhileLoopExample.java
```
While the program running, open another terminal session. In the new terminal use the `jstat` command to print out the JVM statistics specifically related to the GC using the `-gcutil` flag:
While the program is running, open another terminal session.

In the new terminal use the `jstat` command to print out the JVM statistics specifically related to the GC using the `-gcutil` flag:

```bash
jstat -gcutil $(pgrep java) 1000
```

You will observe output like the following until `ctl+c` is pressed.
You will observe output like the following until `ctl+c` is pressed:

```output
S0 S1 E O M CCS YGC YGCT FGC FGCT CGC CGCT GCT
Expand All @@ -125,10 +135,10 @@ You will observe output like the following until `ctl+c` is pressed.
```

The columns of interest are:
- **E (Eden Space Utilization)**: The percentage of the Eden space that is currently used. High utilization indicates frequent allocations and can trigger minor GCs.
- **O (Old Generation Utilization)**: The percentage of the Old (Tenured) generation that is currently used. High utilization can lead to Full GCs, which are more expensive.
- **YGCT (Young Generation GC Time)**: The total time (in seconds) spent in Young Generation (minor) GC events. High values indicate frequent minor GCs, which can impact performance.
- **FGCT (Full GC Time)**: The total time (in seconds) spent in Full GC events. High values indicate frequent Full GCs, which can significantly impact performance.
- **GCT (Total GC Time)**: The total time (in seconds) spent in all GC events (Young, Full, and Concurrent). This provides an overall view of the time spent in GC, helping to assess the impact on application performance.
- **E (Eden Space Utilization)**: The percentage of the Eden space that is being used. High utilization indicates frequent allocations and can trigger minor GCs.
- **O (Old Generation Utilization)**: The percentage of the Old (Tenured) generation that is being used. High utilization can lead to Full GCs, which are more expensive.
- **YGCT (Young Generation GC Time)**: The total time in seconds spent in Young Generation (minor) GC events. High values indicate frequent minor GCs, which can impact performance.
- **FGCT (Full GC Time)**: The total time in seconds spent in Full GC events. High values indicate frequent Full GCs, which can significantly impact performance.
- **GCT (Total GC Time)**: The total time in seconds spent in all GC events (Young, Full, and Concurrent). This provides an overall view of the time spent in GC, helping to assess the impact on application performance.


Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
---
title: Basic GC Tuning Options
weight: 5
weight: 6

### FIXED, DO NOT MODIFY
layout: learningpathall
---

### Update the JDK version

If you are on an older version of JDK, a sensible first step is to use one of the latest long-term-support (LTS) releases of JDK. This is because the GC versions included with recent JDKs offer improvements. For example, the G1GC included with JDK 11 offers improvements in the pause time compared to JDK 8. As shown earlier, you can use the `java --version` command to check the version currently in use.
If you are on an older version of JDK, a sensible first step is to use one of the latest long-term-support (LTS) releases of JDK. This is because the GC versions included with recent JDKs offer improvements on previous releases. For example, the G1GC included with JDK 11 offers improvements in the pause time compared to JDK 8.

As shown earlier, you can use the `java --version` command to check the version currently in use:

```output
$ java --version
Expand All @@ -22,25 +24,27 @@ OpenJDK 64-Bit Server VM Corretto-21.0.4.7.1 (build 21.0.4+7-LTS, mixed mode, sh

In this section, you will use the `HeapUsageExample.java` file you created earlier.

The G1 GC (Garbage-First Garbage Collector) is designed to handle large heaps and aims to provide low pause times by dividing the heap into regions and performing incremental garbage collection. This makes it suitable for applications with high allocation rates and large memory footprints.
The Garbage-First Garbage Collector (G1GC) is designed to handle large heaps and aims to provide low pause times by dividing the heap into regions and performing incremental garbage collection. This makes it suitable for applications with high allocation rates and large memory footprints.

You can run the following command to generate the GC logs using a different GC and compare the two.

You can run the following command to generate the GC logs using a different GC and compare. You just need to change the GC from `Serial` to `G1GC` using the `-XX:+UseG1GC` option as shown:
To make this comparison, change the Garbage Collector from `Serial` to `G1GC` using the `-XX:+UseG1GC` option:

```bash
java -Xms512m -Xmx1024m -XX:+UseG1GC -Xlog:gc:file=gc.log:tags,uptime,time,level:filecount=10,filesize=16m HeapUsageExample.java
```
From the created log file `gc.log`, you can observe that at a very similar time after start up (~0.75s), the Pause Young time reduced from ~3.6ms to ~1.9ms. Further, the time between GC pauses has improved from ~46ms to every ~98ms.
From the created log file `gc.log`, you can see that at a similar time after startup (~0.75s), the Pause Young time reduced from ~3.6ms to ~1.9ms. Further, the time between GC pauses has improved from ~46ms to every ~98ms.

```output
[2024-11-08T16:13:53.088+0000][0.790s][info][gc ] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 307M->3M(514M) 1.976ms
...
[2024-11-08T16:13:53.186+0000][0.888s][info][gc ] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 307M->3M(514M) 1.703ms
```
As discussed in the previous section, the performance improvement from moving to a G1GC will depend on the CPU overhead of your system. The performance may vary depending on the cloud instance size and available CPU resources.
As described in the previous section, the performance improvement from moving to a G1GC depends on the CPU overhead of your system. The performance can vary depending on the cloud instance size and available CPU resources.

### Add GC Targets
### Add Garbage Collector Targets

You can manually provide targets for specific metrics and the GC will attempt to meet those requirements. For example, if you have a time-sensitive application such as a REST server, you may want to ensure that all customers receive a response within a specific time. You may find that if a client request is sent during GC you need to ensure that the GC pause time is minimised.
You can manually provide targets for specific metrics and the GC will attempt to meet those requirements. For example, if you have a time-sensitive application such as a REST server, you might want to ensure that all customers receive a response within a specific time. You might find that if a client request is sent during Garbage Collection that you need to ensure that the GC pause time is minimised.

Running the command with the `-XX:MaxGCPauseMillis=<N>` sets a target max GC pause time:

Expand All @@ -55,19 +59,19 @@ Looking at the output below, you can see that at the same initial state after ~0
[2024-11-08T16:27:37.149+0000][0.853s][info][gc] GC(19) Pause Young (Normal) (G1 Evacuation Pause) 193M->3M(514M) 0.482ms
```

Here are some additional target options you can consider to tune performance:
Here are some additional target options that you can consider to tune performance:

- -XX:InitiatingHeapOccupancyPercent:

Defines the old generation occupancy threshold to trigger a concurrent GC cycle. Adjusting this can be beneficial if your application experiences long GC pauses due to high old generation occupancy. For example, lowering this threshold can help start GC cycles earlier, reducing the likelihood of long pauses during peak memory usage.
This defines the old generation occupancy threshold to trigger a concurrent GC cycle. Adjusting this is beneficial if your application experiences long GC pauses due to high old generation occupancy. For example, lowering this threshold can help start GC cycles earlier, reducing the likelihood of long pauses during peak memory usage.

- -XX:ParallelGCThreads

Specifies the number of threads for parallel GC operations. Increasing this value can be beneficial for applications running on multi-core processors, as it allows GC tasks to be processed faster. For instance, a high-throughput server application might benefit from more parallel GC threads to minimize pause times and improve overall performance.
This specifies the number of threads for parallel GC operations. Increasing this value is beneficial for applications running on multi-core processors, as it allows GC tasks to be processed faster. For instance, a high-throughput server application might benefit from more parallel GC threads to minimize pause times and improve overall performance.

- -XX:G1HeapRegionSize

Determines the size of G1 regions, which must be a power of 2 between 1 MB and 32 MB. Adjusting this can be useful for applications with specific memory usage patterns. For example, setting a larger region size can reduce the number of regions and associated overhead for applications with large heaps, while smaller regions might be better for applications with more granular memory allocation patterns.
This determines the size of G1 regions, which must be a power of 2 between 1 MB and 32 MB. Adjusting this can be useful for applications with specific memory usage patterns. For example, setting a larger region size can reduce the number of regions and associated overhead for applications with large heaps, while smaller regions might be better for applications with more granular memory allocation patterns.

You can refer to [this technical article](https://www.oracle.com/technical-resources/articles/java/g1gc.html) for more information of G1GC tuning.
See [Garbage First Garbage Collector Tuning](https://www.oracle.com/technical-resources/articles/java/g1gc.html) for more information of G1GC tuning.

Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ title: Tune the Performance of the Java Garbage Collector

minutes_to_complete: 45

who_is_this_for: This learning path is designed for Java developers aiming to optimize application performance on Arm-based servers. It is especially valuable for those migrating applications from x86-based to Arm-based instances.
who_is_this_for: This Learning Path is for Java developers aiming to optimize application performance on Arm-based servers, especially those migrating applications from x86-based to Arm-based instances.

learning_objectives:
- Understand the key differences among Java garbage collectors (GCs).
- Monitor and interpret GC performance metrics.
- Describe the key differences between individual Java Garbage Collectors (GCs).
- Monitor and interpret Garbage Collector performance metrics.
- Adjust core parameters to optimize performance for your specific workload.

prerequisites:
- An Arm based instance from a cloud service provider, or an on-premise Arm server.
- Basic understanding of Java and [Java installed](/install-guides/java/) on your machine.
- An Arm-based instance from a cloud service provider, or an on-premise Arm server.
- Basic understanding of Java.
- An [installation of Java](/install-guides/java/) on your machine.

author_primary: Kieran Hejmadi

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@
review:
- questions:
question: >
What is the purpose of garbage collection?
What is the purpose of Garbage Collection?
answers:
- To manage memory by automatically reclaiming unused objects
- To manually manage memory allocation
- To manage memory by automatically reclaiming unused objects.
- To manually manage memory allocation.
correct_answer: 1
explanation: >
Garbage collection is used to manage memory by automatically reclaiming memory occupied by objects that are no longer in use, thus preventing memory leaks and optimizing memory usage.
Garbage Collection is used to manage memory by automatically reclaiming memory occupied by objects that are no longer in use, to prevent memory leaks and optimize memory usage.
- questions:
question: >
Which JVM flag can be used to enable detailed garbage collection logging?
Which JVM flag can you use to enable detailed garbage collection logging?
answers:
- -XX:+UseG1GC
- -XX:+PrintGCDetails
- -XX:+UseG1GC.
- -XX:+PrintGCDetails.
correct_answer: 2
explanation: >
The flag -XX:+PrintGCDetails enables detailed logging of garbage collection events, which helps in monitoring and tuning the GC performance.
- questions:
question: >
Which garbage collector is best suited for applications requiring very low latency in a heavily multi-threaded application?
Which Garbage Collector is best suited for applications requiring very low latency in a heavily multi-threaded application?
answers:
- Serial GC
- ZGC
- Serial GC.
- ZGC.
correct_answer: 2
explanation: >
ZGC (Z Garbage Collector) is designed for applications requiring very low latency, as it aims to keep pause times below 10 milliseconds even for large heaps.
Expand Down
Loading

0 comments on commit 7708c98

Please sign in to comment.