Profiler
The n3Client JVM profiler — resource monitoring, CPU sampling with flame graphs, leak detection, event timeline, JIT and thread analysis, JVMTI diagnostics, and exact method timing.
Comprehensive JVM profiling and performance monitoring tool with advanced visualization and analysis capabilities. Source of truth: docs/PROFILER.md in the n3Client repository.
Overview
The n3Client JVM Profiler is a production-grade profiling tool that provides real-time monitoring, performance analysis, and optimization recommendations for your Java application. It features nine specialized tabs — Resource Monitor, Sampling, Recording, Leak Detector, Event Timeline, JIT Compiler, Threads, VM Configuration, and JVMTI / VM — covering every aspect of JVM performance, from garbage collection to CPU profiling to memory leak detection. Sections 1-8 below document eight of these tabs; the Recording tab (the Exact Timing UI over MethodProfiler) is covered by its API in section 9.
Key features:
- Real-time resource monitoring with customizable time windows
- CPU sampling profiler with interactive flame graphs
- Memory leak detection with treemap visualization
- GC pause analysis with intelligent tuning recommendations
- Event timeline showing unified JVM events
- JIT compiler monitoring with escape analysis insights
- Thread profiling and stack trace analysis
- JVMTI interface for low-level JVM introspection
Access: The Profiler button in the Debug section of the n3Client options panel (N3ClientOptionsPanel), or call ProfilerWindow.toggle() to open/close the profiler. No hotkey is bound.
1. Resource Monitor
Real-time monitoring of CPU, memory, threads, and garbage collection with historical charts and intelligent analysis.
Features
4 live charts:
- CPU & GC Activity: Process CPU usage and garbage collection overhead
- Heap Memory: Used, committed, and max heap memory over time
- Metaspace: Class metadata memory usage and committed space
- Thread Count: Total and daemon thread counts
Summary cards — quick overview cards showing current: CPU usage percentage, GC activity percentage, heap memory (used/max in MB), metaspace (used/committed in MB), thread counts (total with daemon count).
GC pause analysis — real-time analysis of garbage collection pause events.
Statistics: total number of GC pauses, total time spent in GC, average pause duration, 95th and 99th percentile pause times, longest pause with details (type, action, cause, memory freed).
Tuning recommendations with severity levels (SUCCESS, INFO, WARNING, CRITICAL):
- Excessive Pause Times: Detects pauses >500ms (warning) or >1s (critical)
- GC Frequency: Warns if GC occurs >10 times per second
- GC Overhead: Alerts if >5% (warning) or >10% (critical) of runtime spent in GC
- Heap Utilization: Monitors heap pressure and over-provisioning
- Algorithm Detection: Identifies GC algorithm and provides algorithm-specific advice
Example recommendations:
[CRITICAL] Very Long GC Pauses
99th percentile pause time is 1250ms. This can cause severe application lag.
Suggestion: -XX:MaxGCPauseMillis=200 (reduce target pause time)
[WARNING] High Heap Utilization
Heap 85.3% full. Consider increasing heap size.
Suggestion: Increase heap size: -Xmx<larger_value>Controls
- Pause/Resume: Freeze monitoring to analyze current data
- Time Window: Select 1, 2, 5, or 10 minute history windows
- Export CSV: Export metrics to CSV file for external analysis
- Force GC: Trigger System.gc() for immediate garbage collection
- Clear: Reset all charts and history
Best practices
Monitor during load testing — run your application under realistic load while watching the Resource Monitor to identify peak memory usage, GC pause patterns, CPU bottlenecks, and thread count growth.
Use GC recommendations — the tuning advisor provides actionable JVM flags. Test recommendations in staging before production: note the current baseline, apply one recommendation at a time, measure impact with the same workload, keep changes that improve performance.
Set appropriate time windows:
- 1-2 minutes: Quick troubleshooting, identify immediate issues
- 5-10 minutes: Long-term trends, capacity planning
- Steady state: Wait 5+ minutes after startup for JIT warmup
Watch for patterns:
- Sawtooth heap pattern: Normal (allocation → GC → allocation)
- Steadily rising heap: Possible memory leak
- Frequent GC spikes: Heap too small or allocation rate too high
- High CPU with low heap usage: CPU-bound workload (not GC issue)
2. Sampling
CPU profiling through stack trace sampling with interactive flame graph visualization.
Features
CPU sampler — periodically captures stack traces to identify hot methods and call patterns:
- Sample Rate: Interval combo offering 10ms / 25ms / 50ms / 100ms (default 50ms)
- Buffers: Fixed-size ring buffers — the CPU sampler holds 100,000 samples, the memory sampler 10,000 (no buffer-size control)
- Control: Start/Stop/Clear sampling
- Export: Save samples to file for offline analysis
Results sub-tabs — sampling results are presented in four sub-tabs: Method Hotspots (per-method sample counts), Flame Graph (interactive stack visualization, below), Thread Breakdown (table with Thread ID, Thread Name, Samples, CPU Time (ms), Runnable, Blocked, and Waiting columns), and Package Aggregation (samples grouped by package).
Interactive flame graph — visual representation of CPU time spent in each method:
How to read:
- Width: Proportional to CPU time (wider = more samples)
- Height: Call stack depth (bottom = entry points, top = leaf methods)
- Color: Package-based coloring for visual grouping
Interactions:
- Hover: Shows method name, sample count, and percentage
- Click: Zoom into selected method and its callees
- Click Header: Reset zoom to full view
Identifying hotspots:
- Wide boxes at the top = leaf methods consuming CPU
- Wide boxes at bottom = frequently called entry points
- Look for unexpected wide boxes (optimization targets)
Workflow
Basic profiling:
1. Start Sampling → Run your workload → Stop Sampling
2. Switch to Flame Graph tab
3. Look for wide boxes at the top (hot methods)
4. Click to zoom into interesting call paths
5. Optimize the widest leaf methodsFinding CPU bottlenecks:
1. Set sample rate to 10-50ms for fine granularity
2. Sample during high-CPU period
3. In flame graph, identify:
- Wide leaves = expensive methods
- Tall stacks = deep call chains (inlining candidates)
- Unexpected packages = third-party overheadBest practices
Sampling configuration:
- Development: 10-50ms rate (detailed profiling)
- Production: 100ms rate (the slowest interval the combo offers)
- Quick Check: 50ms rate (the default)
Interpreting flame graphs:
- Flat Top: CPU distributed across many methods (normal)
- Narrow Spikes: Deep recursion or specific bottleneck
- Wide Platform: Most time in framework/library code
- Wide Application Code: Optimization opportunity
Common patterns:
- Database Calls: Wide boxes in JDBC/connection code → query optimization needed
- JSON Parsing: Wide boxes in Jackson/Gson → consider faster serialization
- String Operations: Wide boxes in String concat → use StringBuilder
- Reflection: Wide boxes in Method.invoke → cache or use MethodHandles
Performance tips:
- Sampling overhead is minimal (under 1% at 100ms intervals)
- Higher sample rates = more detail but higher overhead
- Sample during steady-state load (skip JIT warmup period)
- Compare before/after flame graphs to validate optimizations
3. Leak Detector
Heap analysis and memory leak detection with table and treemap visualizations.
Features
Heap histogram — table view of all classes loaded in heap: class name, instance count, total memory usage, average instance size. Column sorting is disabled (fixed row order).
Interactive treemap — hierarchical visualization of heap memory distribution:
Layout:
- Root Level: Top 50 packages by memory usage
- Nested Level: Top 20 classes per package
- Rectangle Size: Proportional to memory consumption
- Colors: Size-based gradient (red=large, orange=medium, yellow=small, green=tiny)
Interactions:
- Hover: Shows package/class name and exact byte count
- Click: Drill down into package to see its classes
- Click Breadcrumb: Navigate back up the hierarchy
Identifying leaks:
- Look for unexpectedly large packages/classes
- Drill down to see which classes dominate
- Cross-reference with application logic
- Capture a baseline and check growth after your workload
View toggle — switch between table and treemap views with a single button click.
Baseline & analysis controls:
- Start Monitoring / Stop: Begin or stop periodic heap capture
- Set Baseline: Capture a forced-GC baseline snapshot; growth tracking restarts from this point
- Force GC & Capture: Request a full GC and capture a snapshot immediately
- Refresh Analysis: Re-run leak analysis against the latest data
- Show Treemap: Toggle between the table and treemap views
Workflow
Basic leak detection:
1. Start application and let it warm up
2. Click Set Baseline (forces GC, captures the baseline, resets growth tracking)
3. Run workload that might leak
4. Click Force GC & Capture, then Refresh Analysis
5. Review the suspicious-class table — growth against the baseline is tracked automatically
6. Switch to Treemap view
7. Look for unexpectedly large packages
8. Drill down to identify leak candidatesAnalyzing specific classes:
1. In table view, sort by Total Memory (descending)
2. Check top 10 classes for:
- Business objects that should be GC'd
- Collections that might not be cleared
- Caches without eviction policies
3. Click instance count to see growth trendUsing treemap for visual analysis:
1. Switch to Treemap view
2. Red/large rectangles = memory hogs
3. Click large packages to drill down
4. Compare package proportions to expected distribution
5. Investigate unexpected large classesBest practices
Detecting leaks:
- Growth Pattern: Set a baseline, run the workload 3+ times, and refresh the analysis between runs
- Expected vs Actual: Know your domain objects' expected counts
- After GC: Force GC before snapshot to eliminate transient objects
- Isolation: Test suspected feature in isolation
Common leak patterns:
- Static Collections: HashMap/List in static fields never cleared
- Event Listeners: Registered but never unregistered
- Thread Locals: Not cleaned up after use
- Cache Misuse: Unbounded caches without eviction
- Finalizers: Objects with finalizers accumulating in queue
Memory optimization:
- Large collections dominating heap → Consider pagination or streaming
- Many small objects → Object pooling or primitive collections
- String duplicates → String interning or deduplication
- Large byte arrays → Compression or off-heap storage
Reading treemap:
- Concentrate on red/orange rectangles (largest consumers)
- Package-level view shows architectural memory distribution
- Class-level view shows specific optimization targets
- Breadcrumb shows current focus (Root > package > class)
4. Event Timeline
Unified timeline showing all JVM events across garbage collection, compilation, threads, and system activities.
Features
Event types:
- GC Events: Young, Old, Mixed collections with pause times
- Compilation: JIT compilation of hot methods
- Thread Events: Thread start/stop events
- Safepoints: JVM safepoint operations
- Class Loading: Dynamic class loading events
Event table — chronological list (newest first) with timestamp (HH:mm:ss.SSS), event type, description, duration (if applicable), severity (LOW, MEDIUM, HIGH, CRITICAL).
Event details panel — select any event to view full event type description, exact timestamp, duration, severity level, and detailed event-specific information.
Timeline statistics — real-time summary showing total events captured, breakdown by type (GC, Compilation, Thread), time span covered, and longest event duration.
Use cases
Correlating events:
Problem: Application occasionally freezes
Timeline Analysis:
1. Look for clusters of events around freeze time
2. Check if long GC pauses coincide with freeze
3. Look for thread events (deadlock, excessive creation)
4. Check for safepoint operationsGC pattern analysis:
1. Filter/observe GC events
2. Note frequency of Young vs Old collections
3. Check for Mixed collections (indicates G1GC)
4. Long pauses = upgrade to better GC algorithm
5. Frequent pauses = increase heap sizeCompilation analysis:
1. Watch JIT compilation events
2. Early compilations = hot code identified quickly
3. Late compilations = optimization opportunities
4. Many recompilations = unstable call sitesBest practices
Monitoring production:
- Event timeline has minimal overhead (safe for production)
- Useful for post-mortem analysis of incidents
- Correlate with application logs for full picture
Identifying jitter:
- Look for regular event patterns (normal)
- Irregular bursts of events = jitter
- Long gaps between GC = good (low allocation rate)
- Frequent small GCs = high allocation rate
Thread analysis:
- Thread creation events should be rare after startup
- Frequent thread creation = thread pool misconfiguration
- Thread stops during runtime = possible resource leaks
5. JIT Compiler
Just-In-Time compiler monitoring with compilation statistics and optimization insights.
Features
Compiler status: compiler name (C1, C2, Graal, etc.), total compilation time, time monitoring support, available processors.
Compilation levels — understanding tiered compilation:
- Level 0: Interpreter (no compilation)
- Level 1: C1 Simple (fast compilation, basic optimizations)
- Level 2: C1 Limited Profile (profiling data collection)
- Level 3: C1 Full Profile (extensive profiling)
- Level 4: C2/JVMCI (full optimizations, escape analysis, inlining)
Escape analysis insights — educational content explaining JIT optimizations:
Escape analysis:
- Stack allocation of objects that don't escape
- Scalar replacement (replace object fields with locals)
- Lock elision (remove unnecessary synchronization)
Common optimizations:
- Method inlining (inline small, frequently called methods)
- Loop unrolling (expand loops to reduce branch overhead)
- Dead code elimination (remove unused code paths)
- Constant folding (evaluate constant expressions at compile time)
Performance recommendations based on compilation time overhead:
- Low (under 1s): Healthy, efficient JIT activity
- Moderate (1-5s): Monitor for excessive recompilation
- High (>5s): Possible deoptimization cycles, polymorphism issues
Compilation controls:
- Force Compile: Queue method for compilation at specific level
- Deoptimize All: Force recompilation of all methods (for testing)
- Refresh Stats: Update compilation statistics
Best practices
Understanding warmup:
- JVM starts in interpreter mode (slow)
- Hot methods compile to Level 1 (C1 - fast compile)
- With profiling, promote to Level 4 (C2 - full optimization)
- Warmup takes 30 seconds to 5 minutes depending on workload
Optimizing for JIT:
- Monomorphic Calls: Single implementation = inlining
- Bimorphic Calls: Two implementations = inline both
- Megamorphic Calls: 3+ implementations = no inlining (slow)
- Final Classes/Methods: Enable better inlining decisions
- Small Methods: More likely to be inlined
Avoiding deoptimization:
- Avoid changing class shapes after warmup
- Don't mix types in generic collections
- Stable control flow (avoid exception-based control)
- Consistent call sites (same implementation)
Escape analysis benefits — methods that benefit most:
- Methods creating temporary objects (StringBuilder, arrays)
- Methods using objects only locally (no field assignment)
- Methods with short-lived objects (within scope)
Example of optimization-friendly code (illustrative Java, not client API):
// Good: Object doesn't escape, can be stack-allocated
public long calculateSum(int[] values) {
IntAccumulator buffer = new IntAccumulator(); // Local only
for (int v : values) {
buffer.add(v);
}
return buffer.sum();
}
// Minimal local type used above (standalone-compilable; shadows nothing)
class IntAccumulator {
private long total;
void add(int v) { total += v; }
long sum() { return total; }
}
// Bad: Object escapes to field
private IntAccumulator buffer; // Escapes — cannot be stack-allocated6. Threads
Thread profiling and analysis with stack trace inspection.
Features
Active thread list — shows all threads with thread ID, name, and state (RUNNABLE, WAITING, BLOCKED, etc.).
Stack trace viewer — select any thread to view thread ID and name, current state, blocked time (time waiting for locks), blocked count (number of times blocked), and full stack trace.
Refresh — manual refresh to capture current thread state.
Use cases
Deadlock detection:
1. If application hangs, check Threads tab
2. Look for multiple BLOCKED threads
3. Check stack traces for lock acquisition
4. Identify circular lock dependenciesHigh CPU thread:
1. Sort by thread state (RUNNABLE = consuming CPU)
2. Check stack trace to see what it's executing
3. Look for unexpected loops or busy-waits
4. Compare with Sampling flame graph for confirmationThread leak detection:
1. Note thread count in summary card
2. Run workload
3. Check for growing thread count
4. Investigate newly created threads
5. Look for pool misconfigurationBest practices
Thread states:
- RUNNABLE: Executing code or waiting for OS (normal)
- WAITING: Waiting indefinitely (park, wait)
- TIMED_WAITING: Waiting with timeout (sleep, timed wait)
- BLOCKED: Waiting for monitor lock (contention)
Performance:
- High BLOCKED count = lock contention (use concurrent data structures)
- Many WAITING threads = normal for thread pools
- Unexpected RUNNABLE threads = possible busy-wait or infinite loop
Thread naming — use descriptive thread names for easier debugging:
Thread t = new Thread(task, "MyApp-Worker-" + id);Common issues:
- Thread pools not shutting down (executor.shutdown())
- Fire-and-forget threads never terminating
- Daemon threads preventing JVM shutdown
- Thread locals not cleaned up
7. VM Configuration
JVM and system configuration inspection.
Features
VM flags — display of JVM properties: JVM name, version, vendor, runtime version, specification versions.
Flag modification — not available: the flag action always shows a refusal dialog; VM flags can only be set at JVM startup via command line arguments.
CPU features & system info: available processors (cores), operating system name and version, architecture (x86_64, aarch64, etc.).
Use cases
Validating configuration — check that your production JVM matches expected settings: verify JVM version, confirm OS and architecture, check available cores for thread pool sizing.
Troubleshooting — when debugging issues, capture VM info for bug reports (JVM version specifics), performance comparisons (hardware info), and compatibility checks (OS version).
Best practices
Document your flags — keep a record of JVM flags used in production:
java -XX:+PrintFlagsFinal -version > jvm_flags.txtCommon flags:
-Xmx<size>: Max heap size-Xms<size>: Initial heap size-XX:+UseG1GC: Use G1 garbage collector-XX:MaxGCPauseMillis=<ms>: GC pause time goal-XX:+UseStringDeduplication: Deduplicate strings (G1GC)
8. JVMTI / VM
Low-level JVM Tool Interface monitoring and diagnostics.
Features
Status cards — visual indicators for JVMTI availability, VM interface availability, system cores count.
Live charts:
- Memory Utilization: Progress bar and pie chart
- Thread Analysis: Daemon vs user thread pie chart
- Class Loading: Bar chart of regular, interface, array classes
JVM runtime information: JVM platform (name, version, vendor), operating system details, runtime state (thread count, classes loaded, heap usage), VM initialization level, module system status, direct memory configuration, finalization queue depth.
JVMTI interface components:
- VMObjectAccess: Thread enumeration, object sizing
- AdvancedVMAccess: Class metadata, field offsets
- VM: VM state, initialization levels
Comprehensive diagnostics — run full system diagnostics to generate report with: memory analysis (utilization, GC efficiency), thread analysis (total, alive, daemon counts), class loading analysis (types, counts, percentages), object size verification (test objects), JIT compiler status, JVM runtime arguments.
Use cases
Deep troubleshooting — when standard monitoring isn't enough: run full diagnostics, check JVMTI component availability, analyze memory utilization patterns, review class loading statistics, inspect finalization queue depth.
Production health check — regular diagnostics as baseline: establish normal memory utilization (60-80%), track class loading trends, monitor finalization queue (should be near 0), compare thread counts over time.
Best practices
JVMTI availability:
- Most features available on HotSpot JVM
- Some features require special JVM flags
- GraalVM native-image has limited support
Finalization queue:
- High pending count (>100) = finalizer bottleneck
- Finalizers are deprecated, avoid in new code
- Use try-with-resources instead
Direct memory:
- Shows max direct memory allocation
- Important for NIO, ByteBuffer operations
- Set with
-XX:MaxDirectMemorySize=<size>
9. Exact Timing (MethodProfiler)
Manual method timing for precise, per-invocation measurements with nanosecond precision.
Overview
Unlike sampling-based profiling which estimates time statistically, the MethodProfiler provides exact timing by instrumenting your code directly. This is ideal for:
- Measuring specific code paths with precision
- Benchmarking algorithmic changes
- Profiling hot methods identified by the sampling profiler
- Tracking performance across invocations (min/max/avg)
Trade-off: Manual instrumentation required vs zero estimation error.
Features
Enable/Disable toggle:
- Disabled by default for zero runtime overhead
- Enable via checkbox in UI or
MethodProfiler.setEnabled(true) - When disabled, all profiling calls are no-ops
Timing table — displays all recorded method timings: Method (label you assigned), Calls (total invocation count), Total Time, Avg Time, Min (fastest invocation), Max (slowest invocation).
Heat coloring:
- Red: Avg time ≥100ms (very slow)
- Orange: Avg time ≥10ms (slow)
- Yellow: Avg time ≥1ms (moderate)
- Normal: Avg time under 1ms (fast)
Filter — type in the filter box to show only methods whose names start with the entered prefix. Export respects the current filter.
Usage patterns
Pattern 1: begin/end pairs:
MethodProfiler.begin("MyClass.expensiveMethod");
// ... your code ...
MethodProfiler.end("MyClass.expensiveMethod");Pattern 2: try-with-resources (recommended):
try (var ignored = MethodProfiler.time("MyClass.expensiveMethod")) {
// ... your code ...
}
// Automatically ends timing when scope exitsPattern 3: lambda (void operations):
MethodProfiler.time("MyClass.expensiveMethod", () -> {
// ... your code ...
});Pattern 4: lambda with return value:
Result result = MethodProfiler.timeResult("MyClass.compute", () -> {
return computeExpensiveValue();
});API reference
// Enable/disable profiling
MethodProfiler.setEnabled(boolean enabled);
MethodProfiler.isEnabled();
// Timing methods
MethodProfiler.begin(String label);
MethodProfiler.end(String label);
MethodProfiler.time(String label); // Returns AutoCloseable
MethodProfiler.time(String label, Runnable op); // Times void operation
MethodProfiler.timeResult(String label, Supplier<N>); // Times and returns value
// Data access
MethodProfiler.getAllTimings(); // List sorted by total time
MethodProfiler.getAllTimingsByAverage(); // List sorted by average time
MethodProfiler.getTiming(String label); // Get specific timing
MethodProfiler.hasData(); // Check if any data exists
MethodProfiler.getMethodCount(); // Count of tracked methods
// Reports
MethodProfiler.generateReport(); // Human-readable text report
MethodProfiler.generateCSVReport(); // CSV format for spreadsheets
// Management
MethodProfiler.clear(); // Clear all recorded dataBest practices
Naming conventions:
// Good: Class.method format
MethodProfiler.begin("Walker.buildPath");
MethodProfiler.begin("BoatPathing.expandNeighbors");
// Good: Hierarchical for related operations
MethodProfiler.begin("Pathfinding.total");
MethodProfiler.begin("Pathfinding.astar");
MethodProfiler.begin("Pathfinding.corridor");
// Bad: Vague names
MethodProfiler.begin("step1");
MethodProfiler.begin("loop");Granularity tips:
- Profile at method level first, then drill into loops if needed
- Avoid profiling very fast operations (under 1μs) — overhead may dominate
- Use hierarchical labels for nested timing regions
Production usage:
- Keep
MethodProfiler.setEnabled(false)in production - All calls become no-ops with zero overhead when disabled
- Safe to leave instrumentation in code permanently
Comparing optimizations:
// Before optimization
MethodProfiler.begin("Algorithm.v1");
runOldAlgorithm();
MethodProfiler.end("Algorithm.v1");
// After optimization
MethodProfiler.begin("Algorithm.v2");
runNewAlgorithm();
MethodProfiler.end("Algorithm.v2");
// Compare average times in the Exact Timing tabWorkflow example
Optimizing a hot method:
1. Use Sampling tab to identify hot methods (e.g., "expandNeighbors" at 40%)
2. Add MethodProfiler instrumentation:
try (var t = MethodProfiler.time("expandNeighbors.total")) {
try (var t2 = MethodProfiler.time("expandNeighbors.corridorCheck")) {
// corridor logic
}
try (var t3 = MethodProfiler.time("expandNeighbors.heuristic")) {
// heuristic calculation
}
}
3. Enable recording in Exact Timing tab
4. Run workload
5. Analyze exact breakdown of time within the method
6. Optimize the slowest sub-operation
7. Compare before/after using the timing dataExport formats
Text report:
=== MethodProfiler Report ===
Generated: 2024-01-15T10:30:45
Methods tracked: 5
Total calls: 47,469
Total time: 128.25ms
Method Calls Total Average Min Max
--------------------------------------------------------------------------------------------------------------
Walker.expandNeighbors 47,469 128.25ms 2.70μs 1.20μs 15.30ms
Walker.canBoatFit 187,234 31.50ms 0.17μs 0.08μs 2.10ms
...CSV report:
Method,Calls,TotalMs,AverageMs,MinMs,MaxMs
"Walker.expandNeighbors",47469,128.250000,0.002701,0.001200,15.300000
"Walker.canBoatFit",187234,31.500000,0.000168,0.000080,2.100000General best practices
Performance profiling workflow
1. Establish baseline:
- Run application under normal load
- Monitor for 5-10 minutes (JIT warmup)
- Record resource monitor metrics
- Take heap snapshot
- Capture flame graph sample2. Load testing:
- Gradually increase load
- Watch for resource exhaustion
- Monitor GC pause patterns
- Check thread count growth
- Look for memory leaks3. Identify bottlenecks:
- CPU-bound: Flame graph shows hot methods
- Memory-bound: Heap fills quickly, frequent GC
- I/O-bound: Threads WAITING on I/O
- Lock contention: Threads BLOCKED4. Optimize:
- Apply one change at a time
- Measure impact with profiler
- Compare flame graphs before/after
- Validate with load testingAvoiding common pitfalls
Observer effect:
- Profiling adds overhead (especially sampling)
- Sample at 100ms in production (the slowest interval the combo offers)
- Disable sampling when not actively profiling
Warmup period:
- Don't measure during first 1-2 minutes
- JIT needs time to optimize code
- First runs are not representative
Heap snapshots:
- Taking snapshots triggers full GC
- Avoid during critical operations
- Snapshots are point-in-time (not continuous)
GC tuning:
- Test one flag change at a time
- Document baseline before changes
- Some flags conflict (research before combining)
Production vs development
Development:
- Aggressive sampling (10-50ms)
- Frequent heap snapshots
- Enable all diagnostics
- Experiment with JIT controls
Production:
- Conservative sampling (100ms, the slowest interval offered) or off
- Rare heap snapshots (on-demand only)
- Monitor Resource Monitor continuously
- Event Timeline for correlation
- GC analysis for tuning decisions
Integration with application monitoring
Combine profiler data with: application performance monitoring (APM), log aggregation (correlate events with logs), metrics systems (Prometheus, Grafana), database query analyzers, network monitoring.
Correlation example:
1. APM shows slow endpoint response
2. Profiler flame graph shows hot method in that endpoint
3. Logs show database query during that time
4. Event timeline shows long GC pause during query
5. Conclusion: GC pause interrupted slow query, causing timeoutKeyboard shortcuts
None are implemented — the profiler window binds no hotkeys:
- Open/Close Profiler: the Profiler button in the Debug section of the n3Client options panel (
N3ClientOptionsPanel), or callProfilerWindow.toggle() - Previously documented Ctrl+Tab, F5 and Ctrl+E bindings do not exist in the code
Troubleshooting
Profiler won't open:
- Check if JVMTI is available (run diagnostics)
- Verify JVM supports required features
- Check console for error messages
Charts not updating:
- Ensure auto-refresh is enabled
- Check if monitoring is paused
- Verify timers are running (restart profiler)
High memory usage from profiler:
- Reduce time window (2 minutes instead of 10)
- Stop sampling when not needed
- Clear history buffers
Missing JVMTI features:
- Some JVMs have limited JVMTI support
- Try newer JVM version
- Check if restricted by security manager
- Consult JVM documentation
Advanced tips
Custom export format — modify CSV export to include custom calculated fields, additional metrics, formatted for Excel/BI tools.
Automated profiling — schedule profiling sessions: take heap snapshots every N hours, export metrics to time-series database, trigger sampling during specific events, automated comparison of snapshots.
Remote profiling — the shipped remote surface is a loopback-bound HTTP API, not JMX. Click Start API in the profiler window to launch ProfilerServer:
- Binds to
127.0.0.1only (default port 8787) — no cross-machine access - Serves
/profiler(root/help),/profiler/status,/profiler/exact/*(method timing),/profiler/jfr/*(JFR recording),/profiler/hotspots,/profiler/method,/profiler/cpu/*,/profiler/memory/*,/profiler/resources,/profiler/threads, and/profiler/gc - Query these endpoints from tooling on the same machine (for example
curl http://127.0.0.1:8787/profiler/status) - No JMX client is shipped
Scripting integration — integrate with build/test pipelines: profile performance tests automatically, compare flame graphs between versions, detect performance regressions, generate reports for CI/CD.
References
JVM documentation:
Profiling resources:
GC algorithms:
- G1GC: Low latency, pause time goal-oriented
- ZGC: Ultra-low latency (under 10ms pauses)
- Shenandoah: Concurrent, low pause times
- Parallel GC: High throughput, longer pauses
Version history
Current version: includes all 6 advanced profiling features — GC Pause Analyzer & Tuning Advisor, Event Timeline, Auto-Tuning Advisor (embedded in GC recommendations), Interactive Flame Graph Generator, Memory Layout Visualizer (Treemap), Escape Analysis Insights.
Future enhancements: JFR (Java Flight Recorder) integration, heap dump analysis, allocation profiling, off-heap memory tracking, network I/O profiling, database query profiling integration.
Desktop UI consistency — 2026-11-06
Profiler tabs, timeline, flame/treemap chrome and movement diagnostic windows use the shared Storm grounds and font family. Standard actions retain visible keyboard focus; selected recording rows use a dark ground with readable ink. Category/series colors retain their diagnostic meaning. This UI pass does not change sampling, recording, VM or server contracts. See the UI audit (docs/development/evidence/UI_UX_AUDIT_2026-11-06.md in the repository) for the source inventory and unverified live chart/keyboard/scaling states.
Source map — 2026-11-06
Profiler sources live in base-api/src/main/java/dev/n3u/services/profiler/: the window and tabs (ProfilerWindow, SamplingTab, RecordingTab, LeakDetectorTab, TimelinePanel), JVM access (JVMTI, VM, AdvancedVMAccess, JITCompilerAccess, VMObjectAccess), collection (ResourceMetricsCollector, MetricSnapshot, CircularBuffer), GC (gc/GCPauseAnalyzer, gc/GCPauseEvent, gc/GCTuningAdvisor), leak analysis (leak/LeakDetector, leak/ClassLoaderAnalyzer, leak/LeakSuspicion), sampling (sampling/ — CPUSampler, MemorySampler, heap histogram samplers, SampleAnalyzer, SampleExporter, RingBuffer), timeline (timeline/TimelineCollector, TimelineEvent), visualization (visualization/FlameGraphPanel, visualization/TreemapPanel), and the remote surface (server/ProfilerServer).
The MethodProfiler API block above was verified against base-api/src/main/java/dev/n3u/services/profiler/recording/MethodProfiler.java on 2026-11-06: setEnabled/isEnabled, begin/end, time(String) (returns TimingScope, AutoCloseable), time(String, Runnable), timeResult(String, Supplier), getAllTimings, getAllTimingsByAverage, getTiming, hasData, getMethodCount, generateReport, generateCSVReport, clear — all present with those names. The lightweight dev.n3u.util.Profiler (Start/Stop/StopMS) is a separate legacy timing utility, not the profiler window.
This pass verified the API surface statically; no profiling session was run live, so sample-quality and JVMTI-availability behavior remain as described by the original guide sections.
Mouse Movement
Trajectory-based mouse movement — recording, generation, rapid action mode, every setting and default, common configurations, and the packet-level encoding.
Manager
The n3Client Manager — a standalone desktop app for account portfolios, session import, hiscores collection, evidence-gated statuses, security practices, and proxy-compliance checks.