Optimizing Performance

1. Understanding JIT Compilation

StageDetail
InterpreterRuns bytecode directly
C1 (client)Fast compile, light optimization
C2 (server)Aggressive optimization
GraalOptional Java-written JIT

2. Understanding Tiered Compilation

TierUse
0Interpreter
1–3C1 with varying profiling
4C2 (full optimization)
DefaultOn since JDK 8

3. Using Inlining Optimization

FlagEffect
-XX:MaxInlineSize=NCold method size cap (bytes)
-XX:FreqInlineSize=NHot method size cap
-XX:InlineSmallCode=NNative size cap
Diagnostic-XX:+PrintInlining

4. Understanding Escape Analysis Optimization

OptimizationResult
Scalar replacementObject split into local vars
Stack allocationObject on stack (rarely realized)
Lock elisionDrop synchronized on non-escaped locks

5. Using StringBuilder for Concatenation

CodeCompiled As
a + b + c (single expr)InvokeDynamic StringConcatFactory (Java 9+)
Loop concat with +=StringBuilder per iteration — slow
Manual StringBuilderBest for loops

6. Minimizing Object Creation

PatternUse
Reuse buffersByteBuffer pools
Primitive specializationsIntStream, LongStream
Avoid autoboxingUse Map<Integer> only when needed
Static immutablesHoist constants out of methods

7. Using Primitive Types vs Wrappers

TypeMemory
int4 bytes
Integer16 bytes (header + value + padding)
int[1M]~4 MB
Integer[1M]~20 MB + GC pressure

8. Optimizing Collections

TipDetail
Pre-sizenew ArrayList<>(n) avoids resizes
Initial capacityHashMap: load=0.75; size = expected/0.75
EnumMap / EnumSetBit-packed; use for enum keys
Avoid LinkedListArrayDeque is faster for queues

9. Using Lazy Initialization

PatternUse
Initialization-on-demand holderThread-safe via class init lock
Double-checked lockingUse volatile field
StableValue (preview)Java 24+ replacement

10. Caching Expensive Operations

ToolUse
ConcurrentHashMap.computeIfAbsentAtomic memoize
CaffeineHigh-perf in-process cache
SoftReference cacheGC-sensitive (avoid for hot data)

11. Understanding False Sharing

ConceptDetail
Cache lineTypically 64 bytes
IssueTwo threads write to different fields in same line → invalidation
SymptomScaling failure under high core count

12. Using @Contended Annotation

Example: Padding hot fields

@jdk.internal.vm.annotation.Contended
class Counter { volatile long value; }
AspectDetail
Flag-XX:-RestrictContended for app code
EffectPads field to its own cache line
UseRare; verify with JMH

13. Profiling Hotspots

Hotspot Profiling Workflow

  1. Run with realistic load
  2. Capture JFR or async-profiler sample
  3. Generate flame graph
  4. Identify top stacks and inefficient algorithms
  5. Verify allocation pressure separately (alloc profile)
  6. Microbench specific hot paths with JMH
Anti-patternEffect
Premature optimizationWasted effort, complex code
Optimizing without profileOften wrong target