Skip to main content
Course/Module 12/Topic 2 of 4Advanced

Java Performance Tuning

Master JVM internals and performance tuning — garbage collection, memory management, profiling, and optimizing Java applications.

55 minBy Priygop TeamLast updated: Feb 2026

JVM Internals

  • JVM Memory: Heap (objects — Young Gen + Old Gen), Stack (method frames + local variables), Metaspace (class metadata, replaced PermGen). -Xmx sets max heap, -Xms sets initial heap
  • Garbage Collection: Mark-and-sweep — GC identifies unreachable objects and reclaims memory. Young Gen (minor GC, fast) and Old Gen (major GC, slower). GC pauses stop application threads
  • GC Algorithms: G1GC (default, balanced pause/throughput), ZGC (ultra-low pause < 10ms, Java 15+), Shenandoah (low pause, RedHat). Choose based on latency vs throughput requirements
  • JIT Compilation: JVM initially interprets bytecode, then compiles hot methods to native code — tiered compilation (C1 for fast compilation, C2 for optimized code). This is why Java gets faster over time
  • Memory Leaks: Objects referenced but never used — common: static collections that grow forever, unclosed resources, listener references not removed. Use heap dumps to diagnose
  • Profiling Tools: VisualVM, JConsole (built-in), IntelliJ Profiler, async-profiler — CPU profiling (which methods consume time), heap analysis (which objects consume memory), thread analysis (deadlock detection)

Performance Best Practices

  • String Handling: Use StringBuilder for concatenation in loops (String + creates new objects each time). String.intern() for deduplication. String pool stores literals
  • Collection Sizing: new ArrayList<>(expectedSize) — avoid resize/copy operations. HashMap initial capacity = expected entries / 0.75 (load factor). Use primitives with specialized collections (Eclipse Collections)
  • Lazy Initialization: Don't load data until needed — use Supplier<T>, Optional.orElseGet(), Spring @Lazy. Reduces startup time and memory for rarely-used resources
  • Database Optimization: Batch operations (saveAll vs individual save), connection pooling (HikariCP), query optimization (EXPLAIN ANALYZE), avoid N+1 queries (JOIN FETCH)
  • Caching: @Cacheable (Spring Cache) with Redis/Caffeine — cache expensive computations and database queries. Invalidation strategy is the hard part: TTL, event-based, manual
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep