SlideShare a Scribd company logo
Mattias Jiderhamn – java.jiderhamn.se
Join the war on
Mattias Jiderhamn
ClassLoader leaks
Mattias Jiderhamn – java.jiderhamn.se
java.lang.OutOfMemoryError:
PermGen space
:-(
Metaspace
Mattias Jiderhamn – java.jiderhamn.se
Local dev env
Mattias Jiderhamn – java.jiderhamn.se
Continuous Deploy
.war
Crashing
Mattias Jiderhamn – java.jiderhamn.se
Agenda
What does it mean?
Why does it happen?
Where does it leak?
How to avoid?
OSS examples
Training!
Mattias Jiderhamn – java.jiderhamn.se
What?
Mattias Jiderhamn – java.jiderhamn.se
JVM memory
Stack
Heap
PermGen /
Metaspace
Mattias Jiderhamn – java.jiderhamn.se
JVM memory
Per thread
Local variables and
method parameters
Stack
Mattias Jiderhamn – java.jiderhamn.se
JVM memory
Heap
Young generation
Old generation /
tenured space
Eden
space
Survivor
space
Object instances
Mattias Jiderhamn – java.jiderhamn.se
JVM memory
Permanent Generation
java.lang.Class instances
etc
Named before JEE and
class unloading
Renamed Metaspace in Java 8
Aka Method area
PermGen /
Metaspace
Mattias Jiderhamn – java.jiderhamn.se
java.lang.OutOfMemoryError:
PermGen space / Metaspace
= Too many classes are loaded
What?
Mattias Jiderhamn – java.jiderhamn.se
Why?
Mattias Jiderhamn – java.jiderhamn.se
Reason for OOME
1. Your application is too large
-XX:MaxPermSize=256M
Java 8: Metaspace auto increase by default
2. java.lang.Class instances could not
be garbage collected after redeploy
java.lang.OutOfMemoryError:
PermGen space / Metaspace
Mattias Jiderhamn – java.jiderhamn.se
Reference types
• Strong (i.e. normal) reference
–Never GC:ed if reachable
• Soft reference
–GC:ed before OutOfMemoryError
• Weak reference (WeakHashMap)
–GC:ed when no Strong or Soft refs
• Phantom reference
–… won’t prevent GC
Mattias Jiderhamn – java.jiderhamn.se
Example
Foo
WeakHashMap
Map m = new WeakHashMap();
Foo myFoo = new Foo();
m.put(myFoo, ”bar”);
myFoo = null;
Mattias Jiderhamn – java.jiderhamn.se
GC reachability
GC roots
Mattias Jiderhamn – java.jiderhamn.se
Redeploy
Application Server
ClassLoader
app.war
ClassLoader
app.war’
ClassLoader
app.war’’
Mattias Jiderhamn – java.jiderhamn.se
ClassLoader refs
ClassLoader
Class ClassClass
Instance
Mattias Jiderhamn – java.jiderhamn.se
How leaks happen
Application Server
ClassLoader
Class ClassClass
Instance
GC root
Mattias Jiderhamn – java.jiderhamn.se
Where?
Mattias Jiderhamn – java.jiderhamn.se
Application Server
• Application Server bugs
• Logging frameworks
– Apache Commons Logging
Unless LogFactory.release()
– Log4j - some configs
Unless LogManager.shutdown()
– java.util.logging custom Level
• Bean Validation API (JSR 303)
• Unified Expression Language (javax.el)
?
Mattias Jiderhamn – java.jiderhamn.se
GC roots
• Class loaded by system ClassLoader
– static field in JDK classes (java.* etc)
• Live thread
– Stack – local vars, method params
–java.lang.Thread instance
• Object held as synchronization monitor
• JNI references
• JVM specials…
Mattias Jiderhamn – java.jiderhamn.se
System classes
• java.sql.DriverManager
• Bean introspection cache, shutdown hooks,
custom default Authenticator, custom
security Provider, custom MBeans, custom
ThreadGroup, custom property editor, …
• Reference to contextClassLoader of first caller
Mattias Jiderhamn – java.jiderhamn.se
DriverManager
Mattias Jiderhamn – java.jiderhamn.se
DriverManager
Application Server
app.war
mysql-jdbc.jar
JRE
DriverManager
ClassLoader
com.mysql.jdbc.Driver
1) …
… or 2)
DriverManager.deregisterDriver(…)
Mattias Jiderhamn – java.jiderhamn.se
Context shutdown
public class MyCleanupListener implements
javax.servlet.ServletContextListener {
...
/** Called when application is undeployed */
public void contextDestroyed(
ServletContextEvent servletContextEvent) {
DriverManager.deregisterDriver(…);
}
}
Mattias Jiderhamn – java.jiderhamn.se
Threads
• Thread stack
– Local variables
– Method parameters
• MyThread extends Thread
MyRunnable implements Runnable
• contextClassLoader +
AccessControlContext inherited
– Example HTTP 1.1 Keep-Alive-Timer
Mattias Jiderhamn – java.jiderhamn.se
Context shutdown
public class MyCleanupListener implements
javax.servlet.ServletContextListener {
...
/** Called when application is undeployed */
public void contextDestroyed(
ServletContextEvent servletContextEvent) {
DriverManager.deregisterDriver(…);
// Stop threads here!
}
}
Mattias Jiderhamn – java.jiderhamn.se
Stopping threads
public class MyThread extends Thread {
public void run() {
while(true) { // Bad idea!
// Do something
}
}
}
Mattias Jiderhamn – java.jiderhamn.se
Stopping threads
public class MyThread extends Thread {
private boolean running = true;
public void run() {
while(running) { // Until stopped
// Do something
}
}
public void shutdown() {
running = false;
}
}
private volatile boolean running = true;
Heinz Kabutz / Java Specialists’ - The Law of the Blind Spot
Mattias Jiderhamn – java.jiderhamn.se
Threads
• Thread stack
– Local variables
– Method parameters
• MyThread extends Thread
MyRunnable implements Runnable
• contextClassLoader +
AccessControlContext inherited
– Example HTTP 1.1 Keep-Alive-Timer
• ThreadLocal
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
WeakHashMap<Thread, ?>
ThreadLocal
Thread Foo
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
ThreadLocal JavaDoc:
”Each thread holds an implicit
reference to its copy of a thread-
local variable as long as the thread
is alive and the ThreadLocal
instance is accessible; …”
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
ThreadLocalMap
Entry
Thread
ThreadLocal Foo
put()
set()
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
Pooled threads:
•Threads may outlive ClassLoader
•ThreadLocal → ThreadGlobal!
(?)
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
ThreadLocalMap
Entry
Thread
ThreadLocal Foo
ClassClassLoader
static
Class
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
ThreadLocalMap
Entry
Thread
ThreadLocal Foo
ClassClassLoader
Stale entry
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
ThreadLocalMap JavaDoc:
”However, since reference queues
are not used, stale entries are
guaranteed to be removed only
when the table starts running out
of space”
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
•Custom value (incl references)
–static ThreadLocal = leak
–otherwise = unpredicted GC
•Custom ThreadLocal = no leak
Mattias Jiderhamn – java.jiderhamn.se
ThreadLocal
try {
myThreadLocal.set(foo);
…
}
finally {
myThreadLocal.remove();
}
Always clear your ThreadLocals!
Mattias Jiderhamn – java.jiderhamn.se
Known offenders
Apache ActiveMQ
Apache Axis
Apache Batik
Apache Commons Pool / DBCP
Apache CXF
AWT Toolkit
Bean Validation API / JSR 303
CGLIB (Hibernate / Spring / JBoss /
Apache Geronimo)
dom4j
EclipseLink
GeoTools
Google Guice
Groovy
GWT / javax.imageio
Hessian
iCal4J
Infinispan
IntrospectionUtils
JarURLConnection
Java Advanced Imaging (JAI)
Javassist
Java Cryptography Architecture (JCA)
Java Server Faces 2
javax.security.auth.Policy/login.Configuration
JGroups
Logback
JAXB
Mozilla Rhino
MVEL
OpenOffice Java Uno RunTime (JURT)
Oracle JDBC
RMI
Serialization (<= JDK 1.4.2)
Spring framework
Unified Expression Language / javax.el
URLConnection + HTTP 1.1
XML parsing (DocumentBuilderFactory)
Mattias Jiderhamn – java.jiderhamn.se
How?
Mattias Jiderhamn – java.jiderhamn.se
Leak Prevention Lib
• Application server independent
– Version 2 core module is pure Java SE!
• Covers a lot more than Tomcat
– System class references avoided/cleared
– Threads are stopped
– ThreadLocals are cleared
– Known offenders handled
• Logs warnings
• Apache 2 licensed
– You may modify and redistribute
Mattias Jiderhamn – java.jiderhamn.se
Leak Prevention Lib
Zero runtime dependencies
No required config
Maven pom.xml (Servlet 3.0+):
<dependency>
<groupId>se.jiderhamn.classloader-leak-prevention</groupId>
<artifactId>classloader-leak-prevention-servlet3</artifactId>
<version>2.0.2</version>
</dependency>
Mattias Jiderhamn – java.jiderhamn.se
Tomcat
Bugzilla #48895
ThreadLocalMap
Thread
Cleanup
Thread
remove()
Unsafe!
get()
set()
remove()
Removed in 6.0.27
Tomcat 7.0.6+ renews the thread pool
whenever an application is redeployed.
Disposable threads for lifecycle events.
Bugzilla #49159
Mattias Jiderhamn – java.jiderhamn.se
Leak Prevention Lib
set(null) ThreadLocalMap
Entry
Thread
ThreadLocal Foo
Stale
Cleanup
Thread
Mattias Jiderhamn – java.jiderhamn.se
Open Source
examples
Mattias Jiderhamn – java.jiderhamn.se
Bean Validation API
Version 1.0.0.GA
javax.validation.Validation
Application Server
validation-api-1.0.0.GA.jar
app.war
hibernate-validator.jar
Mattias Jiderhamn – java.jiderhamn.se
javax.el API
javax.el.BeanELResolver
Mattias Jiderhamn – java.jiderhamn.se
Apache CXF
org.apache.cxf.transport.http.CXFAuthenticator
CXF-5442
Mattias Jiderhamn – java.jiderhamn.se
OpenOffice JURT
com.sun.star.lib.util.AsynchronousFinalizer
Mattias Jiderhamn – java.jiderhamn.se
Training!
Gear up!
Mattias Jiderhamn – java.jiderhamn.se
Free tool
Eclipse Memory Analyzer
aka MAT
eclipse.org/mat
Mattias Jiderhamn – java.jiderhamn.se
Heap dump
Run application server with
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/temp
Mattias Jiderhamn – java.jiderhamn.se
Links
Join the fight!
java.jiderhamn.se @mjiderhamn
github.com/mjiderhamn
• ClassLoader Leak Prevention Library
• Step by step guide: acquire heap
dump and analyze for leaks using
Eclipse Memory Analyzer (MAT)
• List of known offenders and links to bug reports
• Submit reports and pull requests!
???

More Related Content

PPTX
Clean Code Principles
PPTX
clean code book summary - uncle bob - English version
PDF
Replication Troubleshooting in Classic VS GTID
PDF
PostgreSQL Tutorial For Beginners | Edureka
PDF
[Pgday.Seoul 2020] SQL Tuning
PDF
DDD 준비 서문래
PDF
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
PDF
An Introduction to Test Driven Development
Clean Code Principles
clean code book summary - uncle bob - English version
Replication Troubleshooting in Classic VS GTID
PostgreSQL Tutorial For Beginners | Edureka
[Pgday.Seoul 2020] SQL Tuning
DDD 준비 서문래
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
An Introduction to Test Driven Development

What's hot (20)

PDF
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
PPTX
MySQL Indexing - Best practices for MySQL 5.6
PPS
JUnit Presentation
PDF
React for Beginners
PPT
Multithread & shared_ptr
PDF
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
PDF
중앙 서버 없는 게임 로직
PPTX
Clean code slide
PDF
송창규, unity build로 빌드타임 반토막내기, NDC2010
PDF
Introduction to segmentation fault handling
PPTX
Software development best practices & coding guidelines
KEY
Clean code and Code Smells
PDF
Altinity Quickstart for ClickHouse-2202-09-15.pdf
PDF
Innodb에서의 Purge 메커니즘 deep internal (by 이근오)
PPTX
Unit Testing in Java
PDF
ClickHouse tips and tricks. Webinar slides. By Robert Hodges, Altinity CEO
PDF
MySQL Administrator 2021 - 네오클로바
PDF
Postgresql database administration volume 1
PDF
Iocp advanced
PPTX
Clean code
[Pgday.Seoul 2021] 2. Porting Oracle UDF and Optimization
MySQL Indexing - Best practices for MySQL 5.6
JUnit Presentation
React for Beginners
Multithread & shared_ptr
[Pgday.Seoul 2017] 7. PostgreSQL DB Tuning 기업사례 - 송춘자
중앙 서버 없는 게임 로직
Clean code slide
송창규, unity build로 빌드타임 반토막내기, NDC2010
Introduction to segmentation fault handling
Software development best practices & coding guidelines
Clean code and Code Smells
Altinity Quickstart for ClickHouse-2202-09-15.pdf
Innodb에서의 Purge 메커니즘 deep internal (by 이근오)
Unit Testing in Java
ClickHouse tips and tricks. Webinar slides. By Robert Hodges, Altinity CEO
MySQL Administrator 2021 - 네오클로바
Postgresql database administration volume 1
Iocp advanced
Clean code
Ad

Viewers also liked (20)

PPTX
Memory Management: What You Need to Know When Moving to Java 8
PPTX
A topology of memory leaks on the JVM
PPT
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJ
PDF
Java 8 Launch - MetaSpaces
PDF
Tools for Metaspace
PPTX
The Java Memory Model
PDF
mjprof: Monadic approach for JVM profiling
ODP
GIT out of Dependency Hell - git submodules
PDF
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
PDF
Coding for Android on steroids with Kotlin
PDF
Taking Kotlin to production, Seriously
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PPT
Classloader leak detection in websphere application server
PDF
No one puts java in the container
ODP
Java GC, Off-heap workshop
PPTX
Deploy and Destroy Complete Test Environments
PPTX
Testing RESTful web services with REST Assured
PDF
JVM Internals (2015)
PDF
Ruby CI with Jenkins
PDF
新版 OutOfMemoryErrorを知る
Memory Management: What You Need to Know When Moving to Java 8
A topology of memory leaks on the JVM
Introduktion till Aspekt-orienterad programmering (AOP) med AspectJ
Java 8 Launch - MetaSpaces
Tools for Metaspace
The Java Memory Model
mjprof: Monadic approach for JVM profiling
GIT out of Dependency Hell - git submodules
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
Coding for Android on steroids with Kotlin
Taking Kotlin to production, Seriously
The Future of Futures - A Talk About Java 8 CompletableFutures
Classloader leak detection in websphere application server
No one puts java in the container
Java GC, Off-heap workshop
Deploy and Destroy Complete Test Environments
Testing RESTful web services with REST Assured
JVM Internals (2015)
Ruby CI with Jenkins
新版 OutOfMemoryErrorを知る
Ad

Similar to ClassLoader Leaks (20)

PDF
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
PPTX
Don't dump thread dumps
PDF
Web Sphere Problem Determination Ext
PDF
An Introduction to Java Compiler and Runtime
PPTX
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
PPTX
PDF
java-monitoring-troubleshooting
PPTX
Diving into Java Class Loader
ODP
Eureka moment
PPTX
Don't dump thread dumps
PDF
Java on Linux for devs and ops
PPTX
How to Troubleshoot 9 Types of OutOfMemoryError
ODP
Eureka moment
PPTX
White and Black Magic on the JVM
PPT
Leak, lock and a long pause
PPTX
How to Troubleshoot 9 Types of OutOfMemoryError Session
PDF
JDK not so hidden treasures
PPTX
How to Troubleshoot 9 Types of OutOfMemoryError
PDF
Spark Summit EU talk by Jaroslav Bachorik and Adrian Popescu
PDF
Extending Spark With Java Agent (handout)
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Don't dump thread dumps
Web Sphere Problem Determination Ext
An Introduction to Java Compiler and Runtime
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
java-monitoring-troubleshooting
Diving into Java Class Loader
Eureka moment
Don't dump thread dumps
Java on Linux for devs and ops
How to Troubleshoot 9 Types of OutOfMemoryError
Eureka moment
White and Black Magic on the JVM
Leak, lock and a long pause
How to Troubleshoot 9 Types of OutOfMemoryError Session
JDK not so hidden treasures
How to Troubleshoot 9 Types of OutOfMemoryError
Spark Summit EU talk by Jaroslav Bachorik and Adrian Popescu
Extending Spark With Java Agent (handout)

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Cloud computing and distributed systems.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Machine learning based COVID-19 study performance prediction
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Cloud computing and distributed systems.
Chapter 3 Spatial Domain Image Processing.pdf
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Machine learning based COVID-19 study performance prediction
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

ClassLoader Leaks

  • 1. Mattias Jiderhamn – java.jiderhamn.se Join the war on Mattias Jiderhamn ClassLoader leaks
  • 2. Mattias Jiderhamn – java.jiderhamn.se java.lang.OutOfMemoryError: PermGen space :-( Metaspace
  • 3. Mattias Jiderhamn – java.jiderhamn.se Local dev env
  • 4. Mattias Jiderhamn – java.jiderhamn.se Continuous Deploy .war Crashing
  • 5. Mattias Jiderhamn – java.jiderhamn.se Agenda What does it mean? Why does it happen? Where does it leak? How to avoid? OSS examples Training!
  • 6. Mattias Jiderhamn – java.jiderhamn.se What?
  • 7. Mattias Jiderhamn – java.jiderhamn.se JVM memory Stack Heap PermGen / Metaspace
  • 8. Mattias Jiderhamn – java.jiderhamn.se JVM memory Per thread Local variables and method parameters Stack
  • 9. Mattias Jiderhamn – java.jiderhamn.se JVM memory Heap Young generation Old generation / tenured space Eden space Survivor space Object instances
  • 10. Mattias Jiderhamn – java.jiderhamn.se JVM memory Permanent Generation java.lang.Class instances etc Named before JEE and class unloading Renamed Metaspace in Java 8 Aka Method area PermGen / Metaspace
  • 11. Mattias Jiderhamn – java.jiderhamn.se java.lang.OutOfMemoryError: PermGen space / Metaspace = Too many classes are loaded What?
  • 12. Mattias Jiderhamn – java.jiderhamn.se Why?
  • 13. Mattias Jiderhamn – java.jiderhamn.se Reason for OOME 1. Your application is too large -XX:MaxPermSize=256M Java 8: Metaspace auto increase by default 2. java.lang.Class instances could not be garbage collected after redeploy java.lang.OutOfMemoryError: PermGen space / Metaspace
  • 14. Mattias Jiderhamn – java.jiderhamn.se Reference types • Strong (i.e. normal) reference –Never GC:ed if reachable • Soft reference –GC:ed before OutOfMemoryError • Weak reference (WeakHashMap) –GC:ed when no Strong or Soft refs • Phantom reference –… won’t prevent GC
  • 15. Mattias Jiderhamn – java.jiderhamn.se Example Foo WeakHashMap Map m = new WeakHashMap(); Foo myFoo = new Foo(); m.put(myFoo, ”bar”); myFoo = null;
  • 16. Mattias Jiderhamn – java.jiderhamn.se GC reachability GC roots
  • 17. Mattias Jiderhamn – java.jiderhamn.se Redeploy Application Server ClassLoader app.war ClassLoader app.war’ ClassLoader app.war’’
  • 18. Mattias Jiderhamn – java.jiderhamn.se ClassLoader refs ClassLoader Class ClassClass Instance
  • 19. Mattias Jiderhamn – java.jiderhamn.se How leaks happen Application Server ClassLoader Class ClassClass Instance GC root
  • 20. Mattias Jiderhamn – java.jiderhamn.se Where?
  • 21. Mattias Jiderhamn – java.jiderhamn.se Application Server • Application Server bugs • Logging frameworks – Apache Commons Logging Unless LogFactory.release() – Log4j - some configs Unless LogManager.shutdown() – java.util.logging custom Level • Bean Validation API (JSR 303) • Unified Expression Language (javax.el) ?
  • 22. Mattias Jiderhamn – java.jiderhamn.se GC roots • Class loaded by system ClassLoader – static field in JDK classes (java.* etc) • Live thread – Stack – local vars, method params –java.lang.Thread instance • Object held as synchronization monitor • JNI references • JVM specials…
  • 23. Mattias Jiderhamn – java.jiderhamn.se System classes • java.sql.DriverManager • Bean introspection cache, shutdown hooks, custom default Authenticator, custom security Provider, custom MBeans, custom ThreadGroup, custom property editor, … • Reference to contextClassLoader of first caller
  • 24. Mattias Jiderhamn – java.jiderhamn.se DriverManager
  • 25. Mattias Jiderhamn – java.jiderhamn.se DriverManager Application Server app.war mysql-jdbc.jar JRE DriverManager ClassLoader com.mysql.jdbc.Driver 1) … … or 2) DriverManager.deregisterDriver(…)
  • 26. Mattias Jiderhamn – java.jiderhamn.se Context shutdown public class MyCleanupListener implements javax.servlet.ServletContextListener { ... /** Called when application is undeployed */ public void contextDestroyed( ServletContextEvent servletContextEvent) { DriverManager.deregisterDriver(…); } }
  • 27. Mattias Jiderhamn – java.jiderhamn.se Threads • Thread stack – Local variables – Method parameters • MyThread extends Thread MyRunnable implements Runnable • contextClassLoader + AccessControlContext inherited – Example HTTP 1.1 Keep-Alive-Timer
  • 28. Mattias Jiderhamn – java.jiderhamn.se Context shutdown public class MyCleanupListener implements javax.servlet.ServletContextListener { ... /** Called when application is undeployed */ public void contextDestroyed( ServletContextEvent servletContextEvent) { DriverManager.deregisterDriver(…); // Stop threads here! } }
  • 29. Mattias Jiderhamn – java.jiderhamn.se Stopping threads public class MyThread extends Thread { public void run() { while(true) { // Bad idea! // Do something } } }
  • 30. Mattias Jiderhamn – java.jiderhamn.se Stopping threads public class MyThread extends Thread { private boolean running = true; public void run() { while(running) { // Until stopped // Do something } } public void shutdown() { running = false; } } private volatile boolean running = true; Heinz Kabutz / Java Specialists’ - The Law of the Blind Spot
  • 31. Mattias Jiderhamn – java.jiderhamn.se Threads • Thread stack – Local variables – Method parameters • MyThread extends Thread MyRunnable implements Runnable • contextClassLoader + AccessControlContext inherited – Example HTTP 1.1 Keep-Alive-Timer • ThreadLocal
  • 32. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal WeakHashMap<Thread, ?> ThreadLocal Thread Foo
  • 33. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal ThreadLocal JavaDoc: ”Each thread holds an implicit reference to its copy of a thread- local variable as long as the thread is alive and the ThreadLocal instance is accessible; …”
  • 34. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal ThreadLocalMap Entry Thread ThreadLocal Foo put() set()
  • 35. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal Pooled threads: •Threads may outlive ClassLoader •ThreadLocal → ThreadGlobal! (?)
  • 36. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal ThreadLocalMap Entry Thread ThreadLocal Foo ClassClassLoader static Class
  • 37. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal ThreadLocalMap Entry Thread ThreadLocal Foo ClassClassLoader Stale entry
  • 38. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal ThreadLocalMap JavaDoc: ”However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space”
  • 39. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal •Custom value (incl references) –static ThreadLocal = leak –otherwise = unpredicted GC •Custom ThreadLocal = no leak
  • 40. Mattias Jiderhamn – java.jiderhamn.se ThreadLocal try { myThreadLocal.set(foo); … } finally { myThreadLocal.remove(); } Always clear your ThreadLocals!
  • 41. Mattias Jiderhamn – java.jiderhamn.se Known offenders Apache ActiveMQ Apache Axis Apache Batik Apache Commons Pool / DBCP Apache CXF AWT Toolkit Bean Validation API / JSR 303 CGLIB (Hibernate / Spring / JBoss / Apache Geronimo) dom4j EclipseLink GeoTools Google Guice Groovy GWT / javax.imageio Hessian iCal4J Infinispan IntrospectionUtils JarURLConnection Java Advanced Imaging (JAI) Javassist Java Cryptography Architecture (JCA) Java Server Faces 2 javax.security.auth.Policy/login.Configuration JGroups Logback JAXB Mozilla Rhino MVEL OpenOffice Java Uno RunTime (JURT) Oracle JDBC RMI Serialization (<= JDK 1.4.2) Spring framework Unified Expression Language / javax.el URLConnection + HTTP 1.1 XML parsing (DocumentBuilderFactory)
  • 42. Mattias Jiderhamn – java.jiderhamn.se How?
  • 43. Mattias Jiderhamn – java.jiderhamn.se Leak Prevention Lib • Application server independent – Version 2 core module is pure Java SE! • Covers a lot more than Tomcat – System class references avoided/cleared – Threads are stopped – ThreadLocals are cleared – Known offenders handled • Logs warnings • Apache 2 licensed – You may modify and redistribute
  • 44. Mattias Jiderhamn – java.jiderhamn.se Leak Prevention Lib Zero runtime dependencies No required config Maven pom.xml (Servlet 3.0+): <dependency> <groupId>se.jiderhamn.classloader-leak-prevention</groupId> <artifactId>classloader-leak-prevention-servlet3</artifactId> <version>2.0.2</version> </dependency>
  • 45. Mattias Jiderhamn – java.jiderhamn.se Tomcat Bugzilla #48895 ThreadLocalMap Thread Cleanup Thread remove() Unsafe! get() set() remove() Removed in 6.0.27 Tomcat 7.0.6+ renews the thread pool whenever an application is redeployed. Disposable threads for lifecycle events. Bugzilla #49159
  • 46. Mattias Jiderhamn – java.jiderhamn.se Leak Prevention Lib set(null) ThreadLocalMap Entry Thread ThreadLocal Foo Stale Cleanup Thread
  • 47. Mattias Jiderhamn – java.jiderhamn.se Open Source examples
  • 48. Mattias Jiderhamn – java.jiderhamn.se Bean Validation API Version 1.0.0.GA javax.validation.Validation Application Server validation-api-1.0.0.GA.jar app.war hibernate-validator.jar
  • 49. Mattias Jiderhamn – java.jiderhamn.se javax.el API javax.el.BeanELResolver
  • 50. Mattias Jiderhamn – java.jiderhamn.se Apache CXF org.apache.cxf.transport.http.CXFAuthenticator CXF-5442
  • 51. Mattias Jiderhamn – java.jiderhamn.se OpenOffice JURT com.sun.star.lib.util.AsynchronousFinalizer
  • 52. Mattias Jiderhamn – java.jiderhamn.se Training! Gear up!
  • 53. Mattias Jiderhamn – java.jiderhamn.se Free tool Eclipse Memory Analyzer aka MAT eclipse.org/mat
  • 54. Mattias Jiderhamn – java.jiderhamn.se Heap dump Run application server with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/temp
  • 55. Mattias Jiderhamn – java.jiderhamn.se Links Join the fight! java.jiderhamn.se @mjiderhamn github.com/mjiderhamn • ClassLoader Leak Prevention Library • Step by step guide: acquire heap dump and analyze for leaks using Eclipse Memory Analyzer (MAT) • List of known offenders and links to bug reports • Submit reports and pull requests! ???

Editor's Notes

  • #3: No serious amount of web development Tomcat + luck
  • #4: Waste of time restarting AS
  • #5: http://commons.wikimedia.org/wiki/File:JBoss_logo.svg obstacle
  • #6: https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html
  • #7: https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html
  • #8: https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html http://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java good picuture at slide 12
  • #9: https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html http://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java
  • #11: Default 64 MB http://java.dzone.com/articles/java-8-permgen-metaspace http://www.infoq.com/news/2013/03/java-8-permgen-metaspace
  • #13: ”All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.”
  • #15: Inspired by http://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java slide 12
  • #16: http://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java slide 12
  • #17: http://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java slide 12
  • #18: Tomcat, Jetty, Resin, possibly GlashFish Bean Validation API
  • #19: GC roots: http://www.yourkit.com/docs/java/help/gc_roots.jsp http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx ÄNDRA: THREAD + underrubriker
  • #20: java.lang.Runtime.getRuntime().addShutdownHook()
  • #24: Runnable
  • #27: ”The Java Memory Model allows each thread to keep a local copy of fields.”
  • #30: Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
  • #31: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #32: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #33: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #34: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #35: ThreadLocalMap JavaDoc
  • #36: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #37: http://wiki.apache.org/tomcat/MemoryLeakProtection#customThreadLocal
  • #41: (except Servlet API…) (to simplify override by inheritance)
  • #43: Unsafe: get(), set(), remove() leads to inconsistent state https://issues.apache.org/bugzilla/show_bug.cgi?id=48895 https://issues.apache.org/bugzilla/show_bug.cgi?id=49159
  • #44: Tried filter first Tomcat 7 has ”filter”(?)
  • #45: Fixed in 1.1
  • #46: Independent of EL implementation Fixed in SVN, still wrong in 2.2.1-b04
  • #49: GC roots: http://www.yourkit.com/docs/java/help/gc_roots.jsp http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx
  • #50: http://commons.wikimedia.org/wiki/File:Duke_Wave.png