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

diabetic retinopathy.pptx
diabetic retinopathy.pptxdiabetic retinopathy.pptx
diabetic retinopathy.pptxKomal Naphade
 
LASIK REFRACTIVE SURGERY DEMYSTIFIED
LASIK REFRACTIVE SURGERY DEMYSTIFIEDLASIK REFRACTIVE SURGERY DEMYSTIFIED
LASIK REFRACTIVE SURGERY DEMYSTIFIEDDINESH and SONALEE
 
Neovascular glaucoma
Neovascular glaucomaNeovascular glaucoma
Neovascular glaucomaBipin Bista
 
Lasers in ophthalmology - Dr. Parag Apte
Lasers in ophthalmology - Dr. Parag ApteLasers in ophthalmology - Dr. Parag Apte
Lasers in ophthalmology - Dr. Parag Apteparag apte
 
Advances in glaucoma-posterior segment evaluation.
Advances in glaucoma-posterior segment evaluation.Advances in glaucoma-posterior segment evaluation.
Advances in glaucoma-posterior segment evaluation.Dr. Stuti Somani Agarwal
 
Phototherapeutic keratectomy By Dr. Safaa Refaat
Phototherapeutic keratectomy By Dr. Safaa RefaatPhototherapeutic keratectomy By Dr. Safaa Refaat
Phototherapeutic keratectomy By Dr. Safaa Refaatsafaa refaat
 
Lasers in ophthalmology
Lasers in ophthalmologyLasers in ophthalmology
Lasers in ophthalmologyNikita Jaiswal
 
Phacomachine and its dynamics
Phacomachine and its dynamicsPhacomachine and its dynamics
Phacomachine and its dynamicsSujay Chauhan
 
CATARACT SURGERY COMPLICATIONS
CATARACT SURGERY COMPLICATIONSCATARACT SURGERY COMPLICATIONS
CATARACT SURGERY COMPLICATIONSSiva Wurity
 
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...DrHussainAhmadKhaqan
 
Phaco - PhacoTrabec.pptx
Phaco - PhacoTrabec.pptxPhaco - PhacoTrabec.pptx
Phaco - PhacoTrabec.pptxdocsarsi
 
Diabetic Retinopathy- PDR and CSME
Diabetic Retinopathy- PDR and CSME Diabetic Retinopathy- PDR and CSME
Diabetic Retinopathy- PDR and CSME Soumik Sen
 
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...BREEZE Software
 
Retinal laser therapy
Retinal laser therapyRetinal laser therapy
Retinal laser therapyShruti Laddha
 
Anophthalmic socket (evisceration, enucleation, exenteration)
Anophthalmic socket (evisceration, enucleation, exenteration) Anophthalmic socket (evisceration, enucleation, exenteration)
Anophthalmic socket (evisceration, enucleation, exenteration) Haitham Al Mahrouqi
 
Anatomy of cornea
Anatomy of corneaAnatomy of cornea
Anatomy of corneaNiKeRIO
 
nonorganic visual blindness.pptx
nonorganic visual blindness.pptxnonorganic visual blindness.pptx
nonorganic visual blindness.pptxGraecia
 

La actualidad más candente (20)

diabetic retinopathy.pptx
diabetic retinopathy.pptxdiabetic retinopathy.pptx
diabetic retinopathy.pptx
 
LASIK REFRACTIVE SURGERY DEMYSTIFIED
LASIK REFRACTIVE SURGERY DEMYSTIFIEDLASIK REFRACTIVE SURGERY DEMYSTIFIED
LASIK REFRACTIVE SURGERY DEMYSTIFIED
 
Neovascular glaucoma
Neovascular glaucomaNeovascular glaucoma
Neovascular glaucoma
 
Lasers in ophthalmology - Dr. Parag Apte
Lasers in ophthalmology - Dr. Parag ApteLasers in ophthalmology - Dr. Parag Apte
Lasers in ophthalmology - Dr. Parag Apte
 
Advances in glaucoma-posterior segment evaluation.
Advances in glaucoma-posterior segment evaluation.Advances in glaucoma-posterior segment evaluation.
Advances in glaucoma-posterior segment evaluation.
 
Phototherapeutic keratectomy By Dr. Safaa Refaat
Phototherapeutic keratectomy By Dr. Safaa RefaatPhototherapeutic keratectomy By Dr. Safaa Refaat
Phototherapeutic keratectomy By Dr. Safaa Refaat
 
Lasers in ophthalmology
Lasers in ophthalmologyLasers in ophthalmology
Lasers in ophthalmology
 
Pathologies in ffa
Pathologies in ffaPathologies in ffa
Pathologies in ffa
 
Phacomachine and its dynamics
Phacomachine and its dynamicsPhacomachine and its dynamics
Phacomachine and its dynamics
 
CATARACT SURGERY COMPLICATIONS
CATARACT SURGERY COMPLICATIONSCATARACT SURGERY COMPLICATIONS
CATARACT SURGERY COMPLICATIONS
 
Anatomy of conjunctiva
Anatomy of conjunctivaAnatomy of conjunctiva
Anatomy of conjunctiva
 
Implantable Collamer (Contact) Lens
Implantable Collamer (Contact) LensImplantable Collamer (Contact) Lens
Implantable Collamer (Contact) Lens
 
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...
Lecture on Squint For 4th Year MBBS Undergraduate Students By Prof. Dr. Hussa...
 
Phaco - PhacoTrabec.pptx
Phaco - PhacoTrabec.pptxPhaco - PhacoTrabec.pptx
Phaco - PhacoTrabec.pptx
 
Diabetic Retinopathy- PDR and CSME
Diabetic Retinopathy- PDR and CSME Diabetic Retinopathy- PDR and CSME
Diabetic Retinopathy- PDR and CSME
 
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...
Comparison of Features and Data Requirements among the CALPUFF, AERMOD, and A...
 
Retinal laser therapy
Retinal laser therapyRetinal laser therapy
Retinal laser therapy
 
Anophthalmic socket (evisceration, enucleation, exenteration)
Anophthalmic socket (evisceration, enucleation, exenteration) Anophthalmic socket (evisceration, enucleation, exenteration)
Anophthalmic socket (evisceration, enucleation, exenteration)
 
Anatomy of cornea
Anatomy of corneaAnatomy of cornea
Anatomy of cornea
 
nonorganic visual blindness.pptx
nonorganic visual blindness.pptxnonorganic visual blindness.pptx
nonorganic visual blindness.pptx
 

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

Último

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

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