SlideShare a Scribd company logo
Java Performance Tuning
@MOHAMMED FAZULUDDIN
Topics
• Overview
• Java Performance Issues And Solutions
• Java Problem Diagnosis
• Java Performance Tuning Tips
• Java Performance Monitoring Tools
Overview
• Java application performance is major concern in most of the
production environments.
• Normally in the production environment we will hear the issues
like…
• The dreaded java.lang.OutOfMemory Error.
• Your application is literally crawling.
• Most of the issues happens because of increasing of heap size and
in proper garbage collection of objects.
• Most of the application which are developed in Java has memory
leakage issue, which will have huge impact on performance.
Overview
• JVM Heap:
• When a Java program started Java Virtual Machine gets some memory
from Operating System. Java Virtual Machine or JVM uses this memory
for all its need and part of this memory is call java heap memory.
• Default size of Heap space in Java is 128MB on most of 32 bit
Sun's JVM but its highly varies from JVM to JVM e.g. default maximum
and start heap size for the 32-bit Solaris Operating System (SPARC
Platform Edition) is -Xms=3670K and -Xmx=64M and Default values
of heap size parameters on 64-bit systems have been increased up by
approximately 30%.
• When JVM starts JVM heap space is equal to the initial size of Heap
specified by -Xms parameter, as application progress more objects get
created and heap space is expanded to accommodate new objects.
Overview
• JVM Heap:
• Java Heap is divided into 3 generations: Young(Eden), Old(Tenured),
and Permanent.
Overview
• Garbage Collection:
• Java has 2 separate threads for GC, one each for young(minor GC) and
old generation(major GC).
• The minor GC (smaller pause, but more frequent) occurs to clean up
garbage in the young generation, while the major GC (larger pause,
but less frequent) cleans up the garbage in the old generation.
• If the major GC too fails to free required memory, the JVM increases
the current memory to help create new object.
• This whole cycle can go on till the current memory reaches the
MaxMemory for the JVM (default is 64MB for client JVM), after which
JVM throws OutOfMemory Error.
Overview
• Garbage Collection:
Overview
• Permanent Generation:
• Class information is stored in the perm generation.
• Also constant strings are stored there.
• Strings created dynamically in your application with String.intern()
will also be stored in the perm generation.
• JVM process memory:
• The windows task manager just shows the memory usage of the
java.exe task/process. It is not unusual for the total memory
consumption of the VM to exceed the value of -Xmx.
• What you see in the TaskManager is the total PAS, while what the
profiler shows is the Java Heap and the PERM(optionally)
Java Performance Issues And Solutions
• Application slow:
• Your application may be crawling because it's spending too much time
cleaning up the garbage , rather than running the app.
Solution: Need to tune the JVM parameters. Take steps to Balance b/w
pause and GC freq.
• Consumes too much memory:
• The memory footprint of the application is related to the number
and size of the live objects that are in the JVM at any given point of
time.
• This can be either due to valid objects that are required to stay in
memory, or because programmer forgot to remove the reference to
unwanted objects (typically known as 'Memory leaks' in java parlance).
Java Performance Issues And Solutions
• Java.lang.OutOfMemoryError can occur due to 3 possible
reasons:
• JavaHeap space low to create new objects, the solution is Increase by -
Xmx (java.lang.OutOfMemoryError: Java heap space).
• java.lang.OutOfMemoryError, the solution is change the Java heap
space MaxHeap=30528 KB TotalHeap=30528 KB FreHeap=170
KB UsedHeap=30357 KB.
• Permanent Generation low, Increase by XX:MaxPermSize=256m
(java.lang.OutOfMemoryError: PermGen space)
java.lang.OutOfMemoryError: PermGen space
MaxHeap=65088 KB TotalHeap=17616 KB FreeHeap=9692
KB UsedHeap=7923 KB
Java Performance Issues And Solutions
• java.lang.OutOfMemoryError: .... Out of swap space ...
• JNI Heap runs low on memory, even though the JavaHeap and the
PermGen have memory.
• This is typically happens if you are making lots of heavy JNI calls, but
the JavaHeap objects occupy little space. In that scenario the GC might
not feel the urge to cleanup JavaHeap, while the JNI Heap keeps on
increasing till it goes out of memory.
• If you use java NIO packages, watch out for this issue. DirectBuffer
allocation uses the native heap.
• The NativeHeap can be increased by -
XX:MaxDirectMemorySize=256M (default is 128)
Java Problem Diagnosis
• There are some starting points to diagnose the problem. You may start
with the '-verbose:gc' flag on the java command and see the memory
footprint as the application progresses, till you find a spike.
• You may analyze the logs or use a light profiler like JConsole (part of
JDK) to check the memory graph.
• If you need the details of the objects that are occupying the memory at a
certain point, then you may use JProfiler or AppPerfect which can
provide the details of each object instance and all the in/out
bound references to/from it.
• This is a memory intensive procedure and not meant for production
systems.
Java Problem Diagnosis
• Some of the diagnosis commands for GC and heap size issues…
• GC outputs:
• -verbose:gc , This flag starts printing additional lines to the console,
like given below
• [GC 65620K -> 50747K(138432K), 0.0279446 secs]
[Full GC 46577K -> 18794K(126848K), 0.2040139 secs]
Combined size of live objects before(young+tenured) GC -> Combined size of live
objects(young+tenured) after GC (Total heap size, not counting the space in the
permanent generation
-XX:+PrintHeapAtGC : More details -XX:+PrintGCTimeStamps will additionally
print a time stamp at the start of each collection.
111.042: [GC 111.042: [DefNew: 8128K->8128K(8128K), 0.0000505 secs]
Java Problem Diagnosis
• hprof output file:
• java –Xrunhprof:heap=sites,cpu=samples,depth=10,thread=y,doe=y
• The heap=sites tells the profiler to write information about memory
utilization on the heap, indicating where it was allocated.
• cpu=samples tells the profiler to do statistical sampling to determine
CPU use.
• depth=10 indicates the depth of the trace for threads.
• thread=y tells the profiler to identify the threads in the stack traces.
• doe=y tells the profiler to produce dump of profiling data on exit.
Java Performance Tuning Tips
• Code change:
• For memory leak issues, it has to be a code change.
• JVM parameters tuning:
• You need to find the behavior of your app in terms of the ratio of young
to old objects, and then tune the JVM accordingly.
• Memory Size: overall size, individual region sizes -ms, -Xms
sets the initial heap size (young and tenured generation ONLY, NOT
Permanent).
• MaxPermSize default value (32mb for -client and 64mb for -
server),tune this to increase the Permanent generation max size.
Java Performance Tuning Tips
• GC parameters:
• -Xminf [0-1], -XX:MinHeapFreeRatio[0-100], sets the percentage of
minimum free heap space - controls heap expansion rate.
• -Xmaxf [0-1], -XX:MaxHeapFreeRatio[0-100], sets the percentage of
maximum free heap space - controls when the VM will return unused
heap memory to the OS.
• -XX:NewRatio, sets the ratio of the old and new generations in the
heap. A NewRatio of 5 sets the ratio of new to old at 1:5, making the
new generation occupy 1/6th of the overall heap.
• -XX:SurvivorRatio, sets the ratio of the survivor space to the eden in
the new object area. A SurvivorRatio of 6 sets the ratio of the three
spaces to 1:1:6, making each survivor space 1/8th of the new object
region.
Java Performance Tuning Tips
• Monitoring the application by software profiling.
• Need to do Server and JVM tuning.
• Use the Right Hardware and OS for the better performance.
• Code improvement as per the Behavior of your application &
profiling results.
• Use JVM the right way : optimal JVM params.
• Minimize the use of synchronization.
• Use -XX:+UseParallelGC if u have multiprocessors.
Java Performance Tuning Tips
• Use multithreading only if it benefits and be aware of the thread
overheads.
• Avoid premature object creation, creation should be as close to the
actual place of use as possible and this is very basic concept that
we tend to overlook.
• Minimize JNI(Java Native Interface) calls in your code.
• Selection of XML APIs , be careful SAX or DOM and make correct
choice.
• Use precompiled xpaths for better performance of the queries.
Java Performance Monitoring Tools
• Jconsole:
• It comes together with JDK 1.5 and above.
• It is a Java Monitoring and Management Console - JMX-compliant
graphical tool for monitoring a Java virtual machine. It can monitor
both local and remote JVMs.
• VisualVM:
• It is a visual tool that integrates several existing JDK software tools and
lightweight memory and CPU profiling capabilities.
• This tool is designed for both production and development time use
and further enhances the capability of monitoring and performance
analysis for the Java SE platform.
Java Performance Monitoring Tools
Jconsole:
Java Performance Monitoring Tools
• HeapAnalyzer:
• Allows the finding of a possible Java™ heap leak area through its heuristic
search engine and analysis of the JavaTM heap dump in Java applications.
• It analyzes Java heap dumps by parsing the Java heap dump, creating
directional graphs, transforming them into directional trees, and executing
the heuristic search engine.
• PerfAnal:
• It is a GUI-based tool for analyzing the performance of applications on the
Java 2 Platform.
• You can use PerfAnal to identify performance problems in your code and
locate code that needs tuning..
Java Performance Monitoring Tools
HeapAnalyzer:
Java Performance Monitoring Tools
• JAMon:
• It is a free, simple, high performance, thread safe, Java API that allows
developers to easily monitor production applications.
• Eclipse Memory Analyzer:
• It is a fast and feature-rich Java heap analyzer that helps you find
memory leaks and reduce memory consumption.
• GCViewer :
• It is a free open source tool to visualize data produced by the Java VM
options -verbose:gc and -Xloggc:<file>.
• It also calculates garbage collection related performance metrics
(throughput, accumulated pauses, longest pause, etc.).
Java Performance Monitoring Tools
JAMon:
Java Performance Monitoring Tools
• AppDynamics:
• Both JConsole and VisualVM ship with the standard Java JDK. These
application performance tools look at your application through the internals
of the JVM run-time, so the metrics they provide are geared towards things
like memory, threads, classes and KPI like JMX metric and MBeans.
• The only drawbacks these tools have is their lack of application context and
ability to run in live production environments continuously, so they can help
developers and support teams pro-actively manage application performance
24/7.
• AppDynamics addresses both limitations of JConsole and VisualVM. It looks
at your JVM through the eyes of your application allowing you to monitor the
performance of business transactions and associated code path execution
whilst your JVM is running in production.
Java Performance Monitoring Tools
AppDynamics :
Java Performance Monitoring Tools
• Stagemonitor:
• Stagemonitor offers a Java monitoring agent, that was built with
clustered application stacks in mind.
• Meaning that it aims to monitor applications that are running on a
number of servers.
• The tool integrates with time series databases (TSDB).
• This tool is optimized for handling time series data, along with arrays
of numbers that are indexed by time.
• These databases include Elasticsearch, Graphite and InfluxDB.
Java Performance Monitoring Tools
• Stagemonitor:
• Stagemonitor includes an agent that sits in your Java application,
sending metrics and request traces to the central database.
• The tool only requires one instance to monitor all applications,
instances and hosts and can be deployed inside your own datacenter.
• On the monitoring side, you can view historical or live data from the
cluster, or directly from the developer server, create custom alerts and
define thresholds for each metric.
• Stagemonitor includes a dashboard, so you can visualize and analyze
the different metrics and requests you’re interested in.
Java Performance Monitoring Tools
Stagemonitor:
Java Performance Monitoring Tools
• Pinpoint:
• Pinpoint is an APM tool made for large scale distributed systems.
• It’s modelled after Dapper, a distributed systems tracing infrastructure
built by Google, providing its developers more information about the
behavior of complex distributed systems.
Java Performance Monitoring Tools
• Pinpoint:
• The tool helps analyze the overall structure of the system and how
components within them are interconnected, by tracing transactions
across distributed applications.
• Meaning that it aims to explain how every transaction gets executed,
trace the flows between the components and (bad joke ahead)
pinpoints problematic areas and potential bottlenecks.
• The dashboard helps visualize how the components are connected, and
lets you monitor active threads inside the applications in real time.
• You can view critical details that include CPU usage, memory/garbage
collection and JVM arguments.
Java Performance Monitoring Tools
• Pinpoint:
Java Performance Monitoring Tools
• MoSKito:
• MoSKito offers 3 tools in one…
• MoSKito-Essential:
• The basic standalone project.
• It’s the core of MoSKito functionality that lets you monitor your application
• MoSKito-Central:
• Centralized storage server for keeping the performance data
• MoSKito-Control:
• A tool for monitoring performance of multi-node web applications
Java Performance Monitoring Tools
• MoSKito:
• To get started, all you need to do is drop the .jar file into the WEB-
INF/lib folder or by including a small new section in the web.xml file.
• Once the tool is up and running, it collects performance data,
analyzing it in real time as well as storing it for historical analysis.
• The tool collects all of your performance metrics, such as threads,
memory, caches, storage, services, registrations, payments, conversion,
SQL, load distribution and so on.
• It doesn’t require code change, supports all of the major app servers
(Tomcat, Jetty, JBoss, WebLogic) and keeps the data locally.
Java Performance Monitoring Tools
• MoSKito:
Java Performance Monitoring Tools
• Glowroot:
• Glowroot prides itself on being a fast, clean and simple APM tool.
• It will allow tracing capture for slow requests and errors, and you’ll be
able to log time trace for each user action, as well as SQL capture and
aggregation.
• The tool also presents a historical rollup of all data with configurable
retention.
• It provides charts to visualize response time breakdown and response
time percentiles, and its responsive UI will allow you to monitor your
application from your mobile devices as well as your desktop.
Java Performance Monitoring Tools
• Glowroot:
• To get started with Glowroot, you need to download and unzip the
main installation file and add -javaagent:path/to/glowroot.jar to your
application’s JVM arguments.
• After you start your application, all that’s left is pointing the browser to
http://localhost:4000.
• Once the tool is up and running, you’ll get continuous profiling (with
filtering options), along with being able to set up alerts for response
time percentiles and MBean attributes.
• Glowroot offers full support for async requests that span multiple
threads, and it supports Tomcat, TomEE, JBoss EAP, Wildfly, Jetty and
Glassfish.
Java Performance Monitoring Tools
• Glowroot:
Java Performance Monitoring Tools
• Kamon:
• Kamon is a reactive-friendly toolkit that is built for applications that
run on top of the JVM.
• More specifically, it’s made for applications that are built with the
Typesafe Reactive Platform (using Scala, Akka, Spray and/or Play!), but
still offers support for any other JVM platforms and languages.
• Kamon is distributed as a core module with all the metric recording
and trace manipulation APIs and optional modules that provide
bytecode instrumentation and/or reporting capabilities to your
application.
• It offers a simple API for recording metrics and trace information for
JVM applications.
Java Performance Monitoring Tools
• Kamon:
• All of Kemon's modules are available through Maven Central, and you
will need to add them as a compile dependency to your project.
• Once you’ve included the modules you’re interested in, simply start up
Kamon, and all of the available modules will be automatically started,
you don’t need to explicitly activate/start them.
• The tracing modules will allow recording data about functionality
executed in your application, and the metrics module will allow you to
control the registration of entities being tracked either by user code or
by instrumentation provided with other Kamon modules.
• It also has other abilities such as filtering, configuring instrument
factories and dispatching metrics subscriptions.
THANKS
• If you feel it is helpful and worthy to share with other people, please share the same

More Related Content

PDF
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
PDF
Java Performance Tuning
PPT
Java Performance Monitoring & Tuning
PDF
Windows Registered I/O (RIO) vs IOCP
PDF
Secrets of Performance Tuning Java on Kubernetes
PDF
Learn Oracle WebLogic Server 12c Administration
PDF
Standard Edition High Availability (SEHA) - The Why, What & How
PPTX
Oracle ASM Training
Disaster Recovery with MirrorMaker 2.0 (Ryanne Dolan, Cloudera) Kafka Summit ...
Java Performance Tuning
Java Performance Monitoring & Tuning
Windows Registered I/O (RIO) vs IOCP
Secrets of Performance Tuning Java on Kubernetes
Learn Oracle WebLogic Server 12c Administration
Standard Edition High Availability (SEHA) - The Why, What & How
Oracle ASM Training

What's hot (20)

PDF
Oracle RAC 19c and Later - Best Practices #OOWLON
PPT
Weblogic Server Overview Weblogic Scripting Tool
PDF
Oracle Real Application Clusters 19c- Best Practices and Internals- EMEA Tour...
PDF
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
PDF
Grokking TechTalk #33: High Concurrency Architecture at TIKI
PPTX
Linux Memory Management with CMA (Contiguous Memory Allocator)
PDF
JVM Performance Tuning
PDF
Choosing Right Garbage Collector to Increase Efficiency of Java Memory Usage
PDF
Intro to Reactive Programming
PPTX
Understanding AntiEntropy in Cassandra
PDF
Android Treble: Blessing or Trouble?
PDF
Clone Oracle Databases In Minutes Without Risk Using Enterprise Manager 13c
PDF
Java Flight Recorder Behind the Scenes
PPTX
Apache spark 소개 및 실습
PDF
malloc & vmalloc in Linux
PPTX
HBase and HDFS: Understanding FileSystem Usage in HBase
PDF
PDF
GPGPU Accelerates PostgreSQL (English)
PDF
Q4.11: Introduction to eMMC
Oracle RAC 19c and Later - Best Practices #OOWLON
Weblogic Server Overview Weblogic Scripting Tool
Oracle Real Application Clusters 19c- Best Practices and Internals- EMEA Tour...
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
Grokking TechTalk #33: High Concurrency Architecture at TIKI
Linux Memory Management with CMA (Contiguous Memory Allocator)
JVM Performance Tuning
Choosing Right Garbage Collector to Increase Efficiency of Java Memory Usage
Intro to Reactive Programming
Understanding AntiEntropy in Cassandra
Android Treble: Blessing or Trouble?
Clone Oracle Databases In Minutes Without Risk Using Enterprise Manager 13c
Java Flight Recorder Behind the Scenes
Apache spark 소개 및 실습
malloc & vmalloc in Linux
HBase and HDFS: Understanding FileSystem Usage in HBase
GPGPU Accelerates PostgreSQL (English)
Q4.11: Introduction to eMMC
Ad

Viewers also liked (19)

PDF
Troubleshooting Java HotSpot VM
PPTX
New Threats, New Approaches in Modern Data Centers
PPTX
Microservices - firststatedot.net - 13-oct-15
PDF
In-Memory Distributed Computing - Porto Tech Hub
PDF
MicroProfile Devoxx.us
PDF
Java EE Microservices
PPTX
Cloud Security
PDF
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux
PPTX
Golang 101 (Concurrency vs Parallelism)
PDF
menRDC - MEN Railway Data Center
PDF
SUSE Expert Days 2017 LENOVO
PDF
Let's Learn to Talk to GC Logs in Java 9
PDF
Lagom, reactive framework(chtijug2016)
PPT
User defined functions in C programmig
PDF
Spring Cloud Contract And Your Microservice Architecture
PPTX
Intro to AWS Machine Learning
PPTX
Apache Spark An Overview
PDF
Lagom : Reactive microservice framework
PDF
Il turismo nello scenario internazionale
Troubleshooting Java HotSpot VM
New Threats, New Approaches in Modern Data Centers
Microservices - firststatedot.net - 13-oct-15
In-Memory Distributed Computing - Porto Tech Hub
MicroProfile Devoxx.us
Java EE Microservices
Cloud Security
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/Linux
Golang 101 (Concurrency vs Parallelism)
menRDC - MEN Railway Data Center
SUSE Expert Days 2017 LENOVO
Let's Learn to Talk to GC Logs in Java 9
Lagom, reactive framework(chtijug2016)
User defined functions in C programmig
Spring Cloud Contract And Your Microservice Architecture
Intro to AWS Machine Learning
Apache Spark An Overview
Lagom : Reactive microservice framework
Il turismo nello scenario internazionale
Ad

Similar to Java performance tuning (20)

PDF
Java Performance and Profiling
PDF
Software Profiling: Java Performance, Profiling and Flamegraphs
PDF
Java Performance and Using Java Flight Recorder
PDF
Tools and Tips to Diagnose Performance Issues
PDF
Software Profiling: Understanding Java Performance and how to profile in Java
ODP
Jvm tuning in a rush! - Lviv JUG
PDF
Java performance - not so scary after all
PDF
TechGIG_Memory leaks in_java_webnair_26th_july_2012
PDF
Taming The JVM
PPTX
Jvm problem diagnostics
PDF
Basics of JVM Tuning
PPTX
PDF
java-monitoring-troubleshooting
PDF
Inside The Java Virtual Machine
PDF
Tuning Java for Big Data
PDF
Troubleshooting Memory Problems in Java Applications
PDF
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
PPTX
Javasession10
PDF
Slices Of Performance in Java - Oleksandr Bodnar
PDF
Java tuning on GNU/Linux for busy dev
Java Performance and Profiling
Software Profiling: Java Performance, Profiling and Flamegraphs
Java Performance and Using Java Flight Recorder
Tools and Tips to Diagnose Performance Issues
Software Profiling: Understanding Java Performance and how to profile in Java
Jvm tuning in a rush! - Lviv JUG
Java performance - not so scary after all
TechGIG_Memory leaks in_java_webnair_26th_july_2012
Taming The JVM
Jvm problem diagnostics
Basics of JVM Tuning
java-monitoring-troubleshooting
Inside The Java Virtual Machine
Tuning Java for Big Data
Troubleshooting Memory Problems in Java Applications
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Javasession10
Slices Of Performance in Java - Oleksandr Bodnar
Java tuning on GNU/Linux for busy dev

More from Mohammed Fazuluddin (20)

PDF
Cloud Providers and Their Key Features Explained
PDF
Database Performance Handling : A comprehensive guide
PDF
Design patterns Q&A | Important question and answers
PDF
Software-Requirements-to-System-Design Basics
PDF
MEAN-vs-MERN-A-Developers-Guide and Explanation
PDF
Cloud AI Deployment Design Patterns - Learn the Basic Deployment Patterns
PDF
Auto-scaling-real-time-software-applications-and-best-practices.pdf
PDF
Java Version(v5 -v23) Features with sample code snippet
PDF
Cloud Architecture Framework Pillar’s.pdf
PDF
Implementing Generative AI and Machine Learning on GCP: Architectures, Use Ca...
PDF
LEVERAGING AWS GENERATIVE AI: ARCHITECTURAL INSIGHTS AND REAL-WORLD IMPLEMENT...
PDF
Basics of GraphQL : Unlocking the Power of GraphQL
PPTX
SQL Injection Introduction and Prevention
PPTX
DOMAIN DRIVER DESIGN
PPTX
New Relic Basics
PPTX
Terraform Basics
PPTX
Rest API Security - A quick understanding of Rest API Security
PPTX
Software architectural patterns - A Quick Understanding Guide
PPTX
Mule ESB - An Enterprise Service Bus
PPTX
Docker - A Quick Introduction Guide
Cloud Providers and Their Key Features Explained
Database Performance Handling : A comprehensive guide
Design patterns Q&A | Important question and answers
Software-Requirements-to-System-Design Basics
MEAN-vs-MERN-A-Developers-Guide and Explanation
Cloud AI Deployment Design Patterns - Learn the Basic Deployment Patterns
Auto-scaling-real-time-software-applications-and-best-practices.pdf
Java Version(v5 -v23) Features with sample code snippet
Cloud Architecture Framework Pillar’s.pdf
Implementing Generative AI and Machine Learning on GCP: Architectures, Use Ca...
LEVERAGING AWS GENERATIVE AI: ARCHITECTURAL INSIGHTS AND REAL-WORLD IMPLEMENT...
Basics of GraphQL : Unlocking the Power of GraphQL
SQL Injection Introduction and Prevention
DOMAIN DRIVER DESIGN
New Relic Basics
Terraform Basics
Rest API Security - A quick understanding of Rest API Security
Software architectural patterns - A Quick Understanding Guide
Mule ESB - An Enterprise Service Bus
Docker - A Quick Introduction Guide

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PDF
Modernizing your data center with Dell and AMD
PDF
Empathic Computing: Creating Shared Understanding
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Electronic commerce courselecture one. Pdf
PPTX
Cloud computing and distributed systems.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
KodekX | Application Modernization Development
Modernizing your data center with Dell and AMD
Empathic Computing: Creating Shared Understanding
Per capita expenditure prediction using model stacking based on satellite ima...
NewMind AI Monthly Chronicles - July 2025
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Mobile App Security Testing_ A Comprehensive Guide.pdf
cuic standard and advanced reporting.pdf
A Presentation on Artificial Intelligence
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Electronic commerce courselecture one. Pdf
Cloud computing and distributed systems.
Dropbox Q2 2025 Financial Results & Investor Presentation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

Java performance tuning

  • 2. Topics • Overview • Java Performance Issues And Solutions • Java Problem Diagnosis • Java Performance Tuning Tips • Java Performance Monitoring Tools
  • 3. Overview • Java application performance is major concern in most of the production environments. • Normally in the production environment we will hear the issues like… • The dreaded java.lang.OutOfMemory Error. • Your application is literally crawling. • Most of the issues happens because of increasing of heap size and in proper garbage collection of objects. • Most of the application which are developed in Java has memory leakage issue, which will have huge impact on performance.
  • 4. Overview • JVM Heap: • When a Java program started Java Virtual Machine gets some memory from Operating System. Java Virtual Machine or JVM uses this memory for all its need and part of this memory is call java heap memory. • Default size of Heap space in Java is 128MB on most of 32 bit Sun's JVM but its highly varies from JVM to JVM e.g. default maximum and start heap size for the 32-bit Solaris Operating System (SPARC Platform Edition) is -Xms=3670K and -Xmx=64M and Default values of heap size parameters on 64-bit systems have been increased up by approximately 30%. • When JVM starts JVM heap space is equal to the initial size of Heap specified by -Xms parameter, as application progress more objects get created and heap space is expanded to accommodate new objects.
  • 5. Overview • JVM Heap: • Java Heap is divided into 3 generations: Young(Eden), Old(Tenured), and Permanent.
  • 6. Overview • Garbage Collection: • Java has 2 separate threads for GC, one each for young(minor GC) and old generation(major GC). • The minor GC (smaller pause, but more frequent) occurs to clean up garbage in the young generation, while the major GC (larger pause, but less frequent) cleans up the garbage in the old generation. • If the major GC too fails to free required memory, the JVM increases the current memory to help create new object. • This whole cycle can go on till the current memory reaches the MaxMemory for the JVM (default is 64MB for client JVM), after which JVM throws OutOfMemory Error.
  • 8. Overview • Permanent Generation: • Class information is stored in the perm generation. • Also constant strings are stored there. • Strings created dynamically in your application with String.intern() will also be stored in the perm generation. • JVM process memory: • The windows task manager just shows the memory usage of the java.exe task/process. It is not unusual for the total memory consumption of the VM to exceed the value of -Xmx. • What you see in the TaskManager is the total PAS, while what the profiler shows is the Java Heap and the PERM(optionally)
  • 9. Java Performance Issues And Solutions • Application slow: • Your application may be crawling because it's spending too much time cleaning up the garbage , rather than running the app. Solution: Need to tune the JVM parameters. Take steps to Balance b/w pause and GC freq. • Consumes too much memory: • The memory footprint of the application is related to the number and size of the live objects that are in the JVM at any given point of time. • This can be either due to valid objects that are required to stay in memory, or because programmer forgot to remove the reference to unwanted objects (typically known as 'Memory leaks' in java parlance).
  • 10. Java Performance Issues And Solutions • Java.lang.OutOfMemoryError can occur due to 3 possible reasons: • JavaHeap space low to create new objects, the solution is Increase by - Xmx (java.lang.OutOfMemoryError: Java heap space). • java.lang.OutOfMemoryError, the solution is change the Java heap space MaxHeap=30528 KB TotalHeap=30528 KB FreHeap=170 KB UsedHeap=30357 KB. • Permanent Generation low, Increase by XX:MaxPermSize=256m (java.lang.OutOfMemoryError: PermGen space) java.lang.OutOfMemoryError: PermGen space MaxHeap=65088 KB TotalHeap=17616 KB FreeHeap=9692 KB UsedHeap=7923 KB
  • 11. Java Performance Issues And Solutions • java.lang.OutOfMemoryError: .... Out of swap space ... • JNI Heap runs low on memory, even though the JavaHeap and the PermGen have memory. • This is typically happens if you are making lots of heavy JNI calls, but the JavaHeap objects occupy little space. In that scenario the GC might not feel the urge to cleanup JavaHeap, while the JNI Heap keeps on increasing till it goes out of memory. • If you use java NIO packages, watch out for this issue. DirectBuffer allocation uses the native heap. • The NativeHeap can be increased by - XX:MaxDirectMemorySize=256M (default is 128)
  • 12. Java Problem Diagnosis • There are some starting points to diagnose the problem. You may start with the '-verbose:gc' flag on the java command and see the memory footprint as the application progresses, till you find a spike. • You may analyze the logs or use a light profiler like JConsole (part of JDK) to check the memory graph. • If you need the details of the objects that are occupying the memory at a certain point, then you may use JProfiler or AppPerfect which can provide the details of each object instance and all the in/out bound references to/from it. • This is a memory intensive procedure and not meant for production systems.
  • 13. Java Problem Diagnosis • Some of the diagnosis commands for GC and heap size issues… • GC outputs: • -verbose:gc , This flag starts printing additional lines to the console, like given below • [GC 65620K -> 50747K(138432K), 0.0279446 secs] [Full GC 46577K -> 18794K(126848K), 0.2040139 secs] Combined size of live objects before(young+tenured) GC -> Combined size of live objects(young+tenured) after GC (Total heap size, not counting the space in the permanent generation -XX:+PrintHeapAtGC : More details -XX:+PrintGCTimeStamps will additionally print a time stamp at the start of each collection. 111.042: [GC 111.042: [DefNew: 8128K->8128K(8128K), 0.0000505 secs]
  • 14. Java Problem Diagnosis • hprof output file: • java –Xrunhprof:heap=sites,cpu=samples,depth=10,thread=y,doe=y • The heap=sites tells the profiler to write information about memory utilization on the heap, indicating where it was allocated. • cpu=samples tells the profiler to do statistical sampling to determine CPU use. • depth=10 indicates the depth of the trace for threads. • thread=y tells the profiler to identify the threads in the stack traces. • doe=y tells the profiler to produce dump of profiling data on exit.
  • 15. Java Performance Tuning Tips • Code change: • For memory leak issues, it has to be a code change. • JVM parameters tuning: • You need to find the behavior of your app in terms of the ratio of young to old objects, and then tune the JVM accordingly. • Memory Size: overall size, individual region sizes -ms, -Xms sets the initial heap size (young and tenured generation ONLY, NOT Permanent). • MaxPermSize default value (32mb for -client and 64mb for - server),tune this to increase the Permanent generation max size.
  • 16. Java Performance Tuning Tips • GC parameters: • -Xminf [0-1], -XX:MinHeapFreeRatio[0-100], sets the percentage of minimum free heap space - controls heap expansion rate. • -Xmaxf [0-1], -XX:MaxHeapFreeRatio[0-100], sets the percentage of maximum free heap space - controls when the VM will return unused heap memory to the OS. • -XX:NewRatio, sets the ratio of the old and new generations in the heap. A NewRatio of 5 sets the ratio of new to old at 1:5, making the new generation occupy 1/6th of the overall heap. • -XX:SurvivorRatio, sets the ratio of the survivor space to the eden in the new object area. A SurvivorRatio of 6 sets the ratio of the three spaces to 1:1:6, making each survivor space 1/8th of the new object region.
  • 17. Java Performance Tuning Tips • Monitoring the application by software profiling. • Need to do Server and JVM tuning. • Use the Right Hardware and OS for the better performance. • Code improvement as per the Behavior of your application & profiling results. • Use JVM the right way : optimal JVM params. • Minimize the use of synchronization. • Use -XX:+UseParallelGC if u have multiprocessors.
  • 18. Java Performance Tuning Tips • Use multithreading only if it benefits and be aware of the thread overheads. • Avoid premature object creation, creation should be as close to the actual place of use as possible and this is very basic concept that we tend to overlook. • Minimize JNI(Java Native Interface) calls in your code. • Selection of XML APIs , be careful SAX or DOM and make correct choice. • Use precompiled xpaths for better performance of the queries.
  • 19. Java Performance Monitoring Tools • Jconsole: • It comes together with JDK 1.5 and above. • It is a Java Monitoring and Management Console - JMX-compliant graphical tool for monitoring a Java virtual machine. It can monitor both local and remote JVMs. • VisualVM: • It is a visual tool that integrates several existing JDK software tools and lightweight memory and CPU profiling capabilities. • This tool is designed for both production and development time use and further enhances the capability of monitoring and performance analysis for the Java SE platform.
  • 20. Java Performance Monitoring Tools Jconsole:
  • 21. Java Performance Monitoring Tools • HeapAnalyzer: • Allows the finding of a possible Java™ heap leak area through its heuristic search engine and analysis of the JavaTM heap dump in Java applications. • It analyzes Java heap dumps by parsing the Java heap dump, creating directional graphs, transforming them into directional trees, and executing the heuristic search engine. • PerfAnal: • It is a GUI-based tool for analyzing the performance of applications on the Java 2 Platform. • You can use PerfAnal to identify performance problems in your code and locate code that needs tuning..
  • 22. Java Performance Monitoring Tools HeapAnalyzer:
  • 23. Java Performance Monitoring Tools • JAMon: • It is a free, simple, high performance, thread safe, Java API that allows developers to easily monitor production applications. • Eclipse Memory Analyzer: • It is a fast and feature-rich Java heap analyzer that helps you find memory leaks and reduce memory consumption. • GCViewer : • It is a free open source tool to visualize data produced by the Java VM options -verbose:gc and -Xloggc:<file>. • It also calculates garbage collection related performance metrics (throughput, accumulated pauses, longest pause, etc.).
  • 25. Java Performance Monitoring Tools • AppDynamics: • Both JConsole and VisualVM ship with the standard Java JDK. These application performance tools look at your application through the internals of the JVM run-time, so the metrics they provide are geared towards things like memory, threads, classes and KPI like JMX metric and MBeans. • The only drawbacks these tools have is their lack of application context and ability to run in live production environments continuously, so they can help developers and support teams pro-actively manage application performance 24/7. • AppDynamics addresses both limitations of JConsole and VisualVM. It looks at your JVM through the eyes of your application allowing you to monitor the performance of business transactions and associated code path execution whilst your JVM is running in production.
  • 26. Java Performance Monitoring Tools AppDynamics :
  • 27. Java Performance Monitoring Tools • Stagemonitor: • Stagemonitor offers a Java monitoring agent, that was built with clustered application stacks in mind. • Meaning that it aims to monitor applications that are running on a number of servers. • The tool integrates with time series databases (TSDB). • This tool is optimized for handling time series data, along with arrays of numbers that are indexed by time. • These databases include Elasticsearch, Graphite and InfluxDB.
  • 28. Java Performance Monitoring Tools • Stagemonitor: • Stagemonitor includes an agent that sits in your Java application, sending metrics and request traces to the central database. • The tool only requires one instance to monitor all applications, instances and hosts and can be deployed inside your own datacenter. • On the monitoring side, you can view historical or live data from the cluster, or directly from the developer server, create custom alerts and define thresholds for each metric. • Stagemonitor includes a dashboard, so you can visualize and analyze the different metrics and requests you’re interested in.
  • 29. Java Performance Monitoring Tools Stagemonitor:
  • 30. Java Performance Monitoring Tools • Pinpoint: • Pinpoint is an APM tool made for large scale distributed systems. • It’s modelled after Dapper, a distributed systems tracing infrastructure built by Google, providing its developers more information about the behavior of complex distributed systems.
  • 31. Java Performance Monitoring Tools • Pinpoint: • The tool helps analyze the overall structure of the system and how components within them are interconnected, by tracing transactions across distributed applications. • Meaning that it aims to explain how every transaction gets executed, trace the flows between the components and (bad joke ahead) pinpoints problematic areas and potential bottlenecks. • The dashboard helps visualize how the components are connected, and lets you monitor active threads inside the applications in real time. • You can view critical details that include CPU usage, memory/garbage collection and JVM arguments.
  • 32. Java Performance Monitoring Tools • Pinpoint:
  • 33. Java Performance Monitoring Tools • MoSKito: • MoSKito offers 3 tools in one… • MoSKito-Essential: • The basic standalone project. • It’s the core of MoSKito functionality that lets you monitor your application • MoSKito-Central: • Centralized storage server for keeping the performance data • MoSKito-Control: • A tool for monitoring performance of multi-node web applications
  • 34. Java Performance Monitoring Tools • MoSKito: • To get started, all you need to do is drop the .jar file into the WEB- INF/lib folder or by including a small new section in the web.xml file. • Once the tool is up and running, it collects performance data, analyzing it in real time as well as storing it for historical analysis. • The tool collects all of your performance metrics, such as threads, memory, caches, storage, services, registrations, payments, conversion, SQL, load distribution and so on. • It doesn’t require code change, supports all of the major app servers (Tomcat, Jetty, JBoss, WebLogic) and keeps the data locally.
  • 35. Java Performance Monitoring Tools • MoSKito:
  • 36. Java Performance Monitoring Tools • Glowroot: • Glowroot prides itself on being a fast, clean and simple APM tool. • It will allow tracing capture for slow requests and errors, and you’ll be able to log time trace for each user action, as well as SQL capture and aggregation. • The tool also presents a historical rollup of all data with configurable retention. • It provides charts to visualize response time breakdown and response time percentiles, and its responsive UI will allow you to monitor your application from your mobile devices as well as your desktop.
  • 37. Java Performance Monitoring Tools • Glowroot: • To get started with Glowroot, you need to download and unzip the main installation file and add -javaagent:path/to/glowroot.jar to your application’s JVM arguments. • After you start your application, all that’s left is pointing the browser to http://localhost:4000. • Once the tool is up and running, you’ll get continuous profiling (with filtering options), along with being able to set up alerts for response time percentiles and MBean attributes. • Glowroot offers full support for async requests that span multiple threads, and it supports Tomcat, TomEE, JBoss EAP, Wildfly, Jetty and Glassfish.
  • 38. Java Performance Monitoring Tools • Glowroot:
  • 39. Java Performance Monitoring Tools • Kamon: • Kamon is a reactive-friendly toolkit that is built for applications that run on top of the JVM. • More specifically, it’s made for applications that are built with the Typesafe Reactive Platform (using Scala, Akka, Spray and/or Play!), but still offers support for any other JVM platforms and languages. • Kamon is distributed as a core module with all the metric recording and trace manipulation APIs and optional modules that provide bytecode instrumentation and/or reporting capabilities to your application. • It offers a simple API for recording metrics and trace information for JVM applications.
  • 40. Java Performance Monitoring Tools • Kamon: • All of Kemon's modules are available through Maven Central, and you will need to add them as a compile dependency to your project. • Once you’ve included the modules you’re interested in, simply start up Kamon, and all of the available modules will be automatically started, you don’t need to explicitly activate/start them. • The tracing modules will allow recording data about functionality executed in your application, and the metrics module will allow you to control the registration of entities being tracked either by user code or by instrumentation provided with other Kamon modules. • It also has other abilities such as filtering, configuring instrument factories and dispatching metrics subscriptions.
  • 41. THANKS • If you feel it is helpful and worthy to share with other people, please share the same