SlideShare a Scribd company logo
1 of 27
Do you really get class loaders? Jevgeni KabanovFounder & CTO of ZeroTurnaround
My Background Creator and core developer of JRebel JRebelmaps your project workspace directly to a running application, watches the changes you make to classes and resources, then intelligently reflects them in your application. With JRebel you can get an extra dev month a year by skipping builds & redeploys 30 day trial, just $149 per developer :)
To create JRebel we… Hooked into class loading on the JVM level Integrated with the class loading mechanism in more than 10 different servers Solved hundreds of issues connected to class loading Learned a lot more about class loaders than we wanted to 
Overview Basics What is class loading? How was it meant to work? Problems and solutions How do class loaders leak? OSGi, Spring dm, JBoss and others Conclusions
Basics
Class loader API publicabstractclassClassLoader {   public Class loadClass(String name);   protected Class defineClass(byte[] b);   public URL getResource(String name);   public Enumeration getResources(String name);   publicClassLoadergetParent() }
Class loading publicclass A { publicvoiddoSmth() {     B b = new B(); b.doSmthElse();   } } Causes a call to A.class.getClassLoader().loadClass(“B”);
Delegation Class loaders have a parent class loader The parent is usually consulted first Avoids loading same class several times However in a Java EE web module local classes are searched first In Java EE each WAR module of an EAR gets its own class loader This allows separate namespaces for applications in same container
Java EE Delegation
Problems and solutions
No class found Variants ClassNotFoundException ClassNoDefFoundException Helpful IDE class lookup (Ctrl+Shift+T in Eclipse) find *.jar -exec jar -tf '{}'  | grepMyClass URLClassLoader.getUrls() Container specific logs
Wrong class found Variants IncompatibleClassChangeError AbstractMethodError NoSuch(Method|Field)FoundError ClassCastException, IllegalAccessError Helpful -verbose:class ClassLoader.getResource() javap -private MyClass
More than one class found Variants LinkageError (class loading constraints violated) ClassCastException, IllegalAccessError Helpful -verbose:class ClassLoader.getResource()
More than one class found Shared ClassLoader ClassCastException Util3 Factory3 Factory3.instanceUntyped(); new Util3() Util3 Test3 Web ClassLoader Util3 u = (Util3) Factory3.instanceUntyped();
More than one class found Shared ClassLoader LinkageError Util3 Factory3 Factory3.instance(); new Util3() Util3 Test4 Web ClassLoader Factory3.instance().sayHello();
More than one class found Shared ClassLoader IllegalAccessError Util3 Factory3 Factory3.instancePackage(); new Util3() Util3 Test5 Web ClassLoader Util3 u = (Util3) Factory3.instancePackage();
Reloading an Object OldClassLoader NewClassLoader MyObject.class MyObject.class Recreate the object MyObject MyObject
Leaking ClassLoaders ClassLoader Class1.class Class2.class Class3.class Static Fields Static Fields Static Fields
Leaking ClassLoaders Example.class Example.class Example.class ExampleFactory$1 ExampleFactory$1 ExampleFactory$1 Leak.class Leak.class Leak.class Leak Leak Leak
State of the art
Hierarchy is not enough? Isolation  Different versions of the same library Performance Class lookup is very slow Restricted Why siblings can’t see each other’s classes? OSGi, JBoss, NetBeans and others implement a different system
The Modern Way Each JAR has own class loader All class loaders are siblings, with one central repository Each JAR explicitly declares Packages it exports Packages it imports Repository can find relevant class loaders by package
Modern Filtering classMClassLoaderextendsClassLoader { // Initialized during startup from imports   Set<String> imps; public Class loadClass(Stringname) {     String pkg = name.substring(0,  name.lastIndexOf('.')); if (!imps.contains(pkg)) returnnull; returnrepository.loadClass(name);   } }
Modern Lookup classMRepository {   // Initialized during startup from exports   Map<String,List<MClassLoader>> exps;   publicClass loadClass(String name) {     String pkg = name.substring(0,     name.lastIndexOf('.'));     for (MClassLoadercl : exps.get(pkg)) {       Class result = cl.loadLocalClass(name);       if (result != null) return result;     }     returnnull;   } }
Troubleshooting The same tricks also work with Modern class loading systems ClassLoader.getResource(); -verbose:class Often can be supplemented with custom tools Need to think in terms of export/import in addition to classpath Looking at the pseudocode can help
Problems Too restrictive Import is a one-way street If you want to use Hibernate, you import it, but it cannot access your classes Easy to leak Any references between class loaders are leaks waiting to happen  Deadlocks JVM enforces a global lock on loadClass()
Conclusions The trick of troubleshooting class loaders is understanding how they work :) Modern systems add a level of complexity on top of an abstraction that nobody gets to begin with When redeploying or reloading classes leaking is easy and leads to OOM We need better tools to troubleshoot class loaders!

More Related Content

What's hot

Fs 1 episode 6 home school link
Fs 1 episode 6 home school linkFs 1 episode 6 home school link
Fs 1 episode 6 home school linkNoel Parohinog
 
Assessment of-student-learning
Assessment of-student-learningAssessment of-student-learning
Assessment of-student-learningalkhaizar
 
Learning activities
Learning activitiesLearning activities
Learning activitiesEMC-DE
 
Reading &amp; writing lesson mts
Reading &amp; writing lesson mtsReading &amp; writing lesson mts
Reading &amp; writing lesson mtsIqbalPancasakti
 
Teaching verbs inductively
Teaching verbs inductivelyTeaching verbs inductively
Teaching verbs inductivelyProf. Richmind
 
Matching Type Test.pptx
Matching Type Test.pptxMatching Type Test.pptx
Matching Type Test.pptxkemrabi1
 
presentation for fs 1.pptx
presentation for fs 1.pptxpresentation for fs 1.pptx
presentation for fs 1.pptxJayleneee
 
5 E Model Lesson Plan- Conservation of Water
5 E Model Lesson Plan-  Conservation of Water5 E Model Lesson Plan-  Conservation of Water
5 E Model Lesson Plan- Conservation of Watermahindravada
 
Field Study 1, Episode 3 "Classroom Management And Learning"
Field Study 1, Episode 3 "Classroom Management And Learning"Field Study 1, Episode 3 "Classroom Management And Learning"
Field Study 1, Episode 3 "Classroom Management And Learning"Ruschelle Cossid
 
Field Study 5 Episode 5
Field Study 5 Episode 5Field Study 5 Episode 5
Field Study 5 Episode 5Jundel Deliman
 
Field study 1(episode 3)
Field study 1(episode 3)Field study 1(episode 3)
Field study 1(episode 3)joshua arisga
 
Fs 5 learning assessment strategies name me
Fs 5 learning assessment strategies   name meFs 5 learning assessment strategies   name me
Fs 5 learning assessment strategies name meJanice Espejo
 
Field Study 1 (Episode 6) - Home School Link
Field Study 1 (Episode 6) - Home School LinkField Study 1 (Episode 6) - Home School Link
Field Study 1 (Episode 6) - Home School LinkAlvin Lim
 

What's hot (20)

Fs 1 episode 6 home school link
Fs 1 episode 6 home school linkFs 1 episode 6 home school link
Fs 1 episode 6 home school link
 
Assessment of-student-learning
Assessment of-student-learningAssessment of-student-learning
Assessment of-student-learning
 
Field study 3 ep6
Field study 3 ep6Field study 3 ep6
Field study 3 ep6
 
Learning activities
Learning activitiesLearning activities
Learning activities
 
FS 1 Episode 7 - Felizarte.docx
FS 1 Episode 7 - Felizarte.docxFS 1 Episode 7 - Felizarte.docx
FS 1 Episode 7 - Felizarte.docx
 
Reading &amp; writing lesson mts
Reading &amp; writing lesson mtsReading &amp; writing lesson mts
Reading &amp; writing lesson mts
 
FS 5 - Episode 7
FS 5 - Episode 7FS 5 - Episode 7
FS 5 - Episode 7
 
Teaching verbs inductively
Teaching verbs inductivelyTeaching verbs inductively
Teaching verbs inductively
 
Matching Type Test.pptx
Matching Type Test.pptxMatching Type Test.pptx
Matching Type Test.pptx
 
presentation for fs 1.pptx
presentation for fs 1.pptxpresentation for fs 1.pptx
presentation for fs 1.pptx
 
5 E Model Lesson Plan- Conservation of Water
5 E Model Lesson Plan-  Conservation of Water5 E Model Lesson Plan-  Conservation of Water
5 E Model Lesson Plan- Conservation of Water
 
Episode 2
Episode 2Episode 2
Episode 2
 
Field Study 1, Episode 3 "Classroom Management And Learning"
Field Study 1, Episode 3 "Classroom Management And Learning"Field Study 1, Episode 3 "Classroom Management And Learning"
Field Study 1, Episode 3 "Classroom Management And Learning"
 
Field Study 5 Episode 5
Field Study 5 Episode 5Field Study 5 Episode 5
Field Study 5 Episode 5
 
Field study 1(episode 3)
Field study 1(episode 3)Field study 1(episode 3)
Field study 1(episode 3)
 
Semi-Detailed Lesson Plan
Semi-Detailed Lesson PlanSemi-Detailed Lesson Plan
Semi-Detailed Lesson Plan
 
Fs 5 learning assessment strategies name me
Fs 5 learning assessment strategies   name meFs 5 learning assessment strategies   name me
Fs 5 learning assessment strategies name me
 
Creating Performance Tasks Easy Steps
Creating Performance Tasks Easy StepsCreating Performance Tasks Easy Steps
Creating Performance Tasks Easy Steps
 
Field Study 1 (Episode 6) - Home School Link
Field Study 1 (Episode 6) - Home School LinkField Study 1 (Episode 6) - Home School Link
Field Study 1 (Episode 6) - Home School Link
 
FS 1 Episode 10 - Felizarte.docx
FS 1 Episode 10 - Felizarte.docxFS 1 Episode 10 - Felizarte.docx
FS 1 Episode 10 - Felizarte.docx
 

Similar to Do you really get class loaders?

Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading tips and tricks - Java Colombo Meetup, January, 2014Sameera Jayasoma
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpathAlexis Hassler
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers GuideDaisyWatson5
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class LoaderKaniska Mandal
 
Java class loader
Java class loaderJava class loader
Java class loaderbenewu
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorialDima Statz
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 

Similar to Do you really get class loaders? (20)

Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading tips and tricks - Java Colombo Meetup, January, 2014
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
 
Java mcq
Java mcqJava mcq
Java mcq
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class Loader
 
Java class loader
Java class loaderJava class loader
Java class loader
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java Class Loading
Java Class LoadingJava Class Loading
Java Class Loading
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
 
Class
ClassClass
Class
 
Class
ClassClass
Class
 
Class
ClassClass
Class
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 

Recently uploaded (20)

The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Do you really get class loaders?

  • 1. Do you really get class loaders? Jevgeni KabanovFounder & CTO of ZeroTurnaround
  • 2. My Background Creator and core developer of JRebel JRebelmaps your project workspace directly to a running application, watches the changes you make to classes and resources, then intelligently reflects them in your application. With JRebel you can get an extra dev month a year by skipping builds & redeploys 30 day trial, just $149 per developer :)
  • 3. To create JRebel we… Hooked into class loading on the JVM level Integrated with the class loading mechanism in more than 10 different servers Solved hundreds of issues connected to class loading Learned a lot more about class loaders than we wanted to 
  • 4. Overview Basics What is class loading? How was it meant to work? Problems and solutions How do class loaders leak? OSGi, Spring dm, JBoss and others Conclusions
  • 6. Class loader API publicabstractclassClassLoader { public Class loadClass(String name); protected Class defineClass(byte[] b); public URL getResource(String name); public Enumeration getResources(String name); publicClassLoadergetParent() }
  • 7. Class loading publicclass A { publicvoiddoSmth() { B b = new B(); b.doSmthElse(); } } Causes a call to A.class.getClassLoader().loadClass(“B”);
  • 8. Delegation Class loaders have a parent class loader The parent is usually consulted first Avoids loading same class several times However in a Java EE web module local classes are searched first In Java EE each WAR module of an EAR gets its own class loader This allows separate namespaces for applications in same container
  • 11. No class found Variants ClassNotFoundException ClassNoDefFoundException Helpful IDE class lookup (Ctrl+Shift+T in Eclipse) find *.jar -exec jar -tf '{}' | grepMyClass URLClassLoader.getUrls() Container specific logs
  • 12. Wrong class found Variants IncompatibleClassChangeError AbstractMethodError NoSuch(Method|Field)FoundError ClassCastException, IllegalAccessError Helpful -verbose:class ClassLoader.getResource() javap -private MyClass
  • 13. More than one class found Variants LinkageError (class loading constraints violated) ClassCastException, IllegalAccessError Helpful -verbose:class ClassLoader.getResource()
  • 14. More than one class found Shared ClassLoader ClassCastException Util3 Factory3 Factory3.instanceUntyped(); new Util3() Util3 Test3 Web ClassLoader Util3 u = (Util3) Factory3.instanceUntyped();
  • 15. More than one class found Shared ClassLoader LinkageError Util3 Factory3 Factory3.instance(); new Util3() Util3 Test4 Web ClassLoader Factory3.instance().sayHello();
  • 16. More than one class found Shared ClassLoader IllegalAccessError Util3 Factory3 Factory3.instancePackage(); new Util3() Util3 Test5 Web ClassLoader Util3 u = (Util3) Factory3.instancePackage();
  • 17. Reloading an Object OldClassLoader NewClassLoader MyObject.class MyObject.class Recreate the object MyObject MyObject
  • 18. Leaking ClassLoaders ClassLoader Class1.class Class2.class Class3.class Static Fields Static Fields Static Fields
  • 19. Leaking ClassLoaders Example.class Example.class Example.class ExampleFactory$1 ExampleFactory$1 ExampleFactory$1 Leak.class Leak.class Leak.class Leak Leak Leak
  • 21. Hierarchy is not enough? Isolation Different versions of the same library Performance Class lookup is very slow Restricted Why siblings can’t see each other’s classes? OSGi, JBoss, NetBeans and others implement a different system
  • 22. The Modern Way Each JAR has own class loader All class loaders are siblings, with one central repository Each JAR explicitly declares Packages it exports Packages it imports Repository can find relevant class loaders by package
  • 23. Modern Filtering classMClassLoaderextendsClassLoader { // Initialized during startup from imports Set<String> imps; public Class loadClass(Stringname) { String pkg = name.substring(0, name.lastIndexOf('.')); if (!imps.contains(pkg)) returnnull; returnrepository.loadClass(name); } }
  • 24. Modern Lookup classMRepository { // Initialized during startup from exports Map<String,List<MClassLoader>> exps; publicClass loadClass(String name) { String pkg = name.substring(0, name.lastIndexOf('.')); for (MClassLoadercl : exps.get(pkg)) { Class result = cl.loadLocalClass(name); if (result != null) return result; } returnnull; } }
  • 25. Troubleshooting The same tricks also work with Modern class loading systems ClassLoader.getResource(); -verbose:class Often can be supplemented with custom tools Need to think in terms of export/import in addition to classpath Looking at the pseudocode can help
  • 26. Problems Too restrictive Import is a one-way street If you want to use Hibernate, you import it, but it cannot access your classes Easy to leak Any references between class loaders are leaks waiting to happen Deadlocks JVM enforces a global lock on loadClass()
  • 27. Conclusions The trick of troubleshooting class loaders is understanding how they work :) Modern systems add a level of complexity on top of an abstraction that nobody gets to begin with When redeploying or reloading classes leaking is easy and leads to OOM We need better tools to troubleshoot class loaders!

Editor's Notes

  1. Class loaders are Java objectsClass loaders are responsible forFinding resourcesResolving class names into Class objectsOriginally motivated by applets
  2. Every class has a reference to its class loader objectMyClass.class.getClassLoader()