CodeBlanks Logo Icon CodeBlanks

Summary - Performance and GC

Combine JMH, JFR and GC tuning to write an optimized handler.

Summary - Performance and GC

In this group you met the performance toolkit. You learned microbenchmarking with JMH, profiling with JFR, latency and throughput balance with GC tuning, memory leaks with heap dumps and run-time compilation with JIT.

The right path: measure first with JMH and JFR, then tune GC and heap, and look at JIT flags only if needed. Premature tuning misleads.

Practice Write the PerfReport class

Define class PerfReport with a static String summary(String tool, String detail) method that returns tool + ": " + detail. In main print System.out.println(summary("JMH", "warmup=3 iters=5"));.

Starter code

Main.java
// Define the PerfReport class: summary method builds the tool summary

// main: print the summary for JMH

Sample solution

Main.java
class PerfReport {
    static String summary(String tool, String detail) {
        return tool + ": " + detail;
    }

    public static void main(String[] args) {
        System.out.println(summary("JMH", "warmup=3 iters=5"));
    }
}

Expected output

JMH: warmup=3 iters=5

What you learned

You can now solve performance issues step by step: measure the bottleneck with JMH, take a production profile with JFR, reduce latency with GC and heap tuning, find leaks with heap dumps. The JIT mostly works behind the scenes.

The key principle: do not tune without measuring. After every change measure again; confirm the improvement with numbers.

Practice Add a report method to PerfReport

Add a static String report() method to the PerfReport class above; it returns summary("JMH", "warmup=3") + " | " + summary("JFR", "duration=60s"). In main print it with System.out.println(report());.

Starter code

Main.java
class PerfReport {
    static String summary(String tool, String detail) {
        return tool + ": " + detail;
    }

    public static void main(String[] args) {
        System.out.println(summary("JMH", "warmup=3 iters=5"));
    }
}

Sample solution

Main.java
class PerfReport {
    static String summary(String tool, String detail) {
        return tool + ": " + detail;
    }
    static String report() {
        return summary("JMH", "warmup=3") + " | " + summary("JFR", "duration=60s");
    }

    public static void main(String[] args) {
        System.out.println(report());
    }
}

Expected output

JMH: warmup=3 | JFR: duration=60s

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool is used for microbenchmarking?

  • JMH Correct answer
  • JFR
  • jcmd
  • JIT

Explanation: JMH measures small code pieces accurately.

2 Summarise the tools

Term Meaning
JMH Benchmarking
JFR Profiling
G1 Garbage collector
JIT Just-in-time compile

All lessons in Expert