SlideShare una empresa de Scribd logo
1 de 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!

Más contenido relacionado

La actualidad más candente

Hashem Q M12_2017 MRCOGP2 revision course
Hashem Q M12_2017 MRCOGP2 revision courseHashem Q M12_2017 MRCOGP2 revision course
Hashem Q M12_2017 MRCOGP2 revision courseHashem Yaseen
 
Fetal assessment and prenatal diagnosis
Fetal assessment and prenatal diagnosisFetal assessment and prenatal diagnosis
Fetal assessment and prenatal diagnosisDrhunny88
 
Decreased fetal movements 2017
Decreased fetal movements 2017Decreased fetal movements 2017
Decreased fetal movements 2017Ahmad Saber
 
Surgical Site Infection (Obstetrics and Gynaecology)
Surgical Site Infection (Obstetrics and Gynaecology)Surgical Site Infection (Obstetrics and Gynaecology)
Surgical Site Infection (Obstetrics and Gynaecology)Kervindran Mohanasundaram
 
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptx
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptxMAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptx
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptxArfiGraphy
 
Heart diseases in pregnancy
Heart diseases in pregnancyHeart diseases in pregnancy
Heart diseases in pregnancyDeepak Chinagi
 
HIV IN PREGNANCY 2017
HIV IN PREGNANCY 2017HIV IN PREGNANCY 2017
HIV IN PREGNANCY 2017Helen Madamba
 
SEJARAH PERANG KHANDAQ
SEJARAH PERANG KHANDAQSEJARAH PERANG KHANDAQ
SEJARAH PERANG KHANDAQdayat7
 

La actualidad más candente (13)

Hashem Q M12_2017 MRCOGP2 revision course
Hashem Q M12_2017 MRCOGP2 revision courseHashem Q M12_2017 MRCOGP2 revision course
Hashem Q M12_2017 MRCOGP2 revision course
 
Fetal assessment and prenatal diagnosis
Fetal assessment and prenatal diagnosisFetal assessment and prenatal diagnosis
Fetal assessment and prenatal diagnosis
 
Ormeloxifene copy
Ormeloxifene   copyOrmeloxifene   copy
Ormeloxifene copy
 
Rh isoimmunisation
Rh isoimmunisationRh isoimmunisation
Rh isoimmunisation
 
Antenatal care.
Antenatal care.Antenatal care.
Antenatal care.
 
Decreased fetal movements 2017
Decreased fetal movements 2017Decreased fetal movements 2017
Decreased fetal movements 2017
 
Post term pregnancy
Post term pregnancyPost term pregnancy
Post term pregnancy
 
Chickenpox in pregnancy
Chickenpox in pregnancyChickenpox in pregnancy
Chickenpox in pregnancy
 
Surgical Site Infection (Obstetrics and Gynaecology)
Surgical Site Infection (Obstetrics and Gynaecology)Surgical Site Infection (Obstetrics and Gynaecology)
Surgical Site Infection (Obstetrics and Gynaecology)
 
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptx
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptxMAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptx
MAKALAH TENTANG KITAB AL- SAMARQANDI ( BAHRUL ULUM).pptx
 
Heart diseases in pregnancy
Heart diseases in pregnancyHeart diseases in pregnancy
Heart diseases in pregnancy
 
HIV IN PREGNANCY 2017
HIV IN PREGNANCY 2017HIV IN PREGNANCY 2017
HIV IN PREGNANCY 2017
 
SEJARAH PERANG KHANDAQ
SEJARAH PERANG KHANDAQSEJARAH PERANG KHANDAQ
SEJARAH PERANG KHANDAQ
 

Similar a 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 a 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
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java 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
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.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!

Notas del editor

  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()