SlideShare ist ein Scribd-Unternehmen logo
1 von 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!

Weitere ähnliche Inhalte

Was ist angesagt?

CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016] CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016]
IO Visor Project
 

Was ist angesagt? (20)

OpenStack API's and WSGI
OpenStack API's and WSGIOpenStack API's and WSGI
OpenStack API's and WSGI
 
Hardening Kafka Replication
Hardening Kafka Replication Hardening Kafka Replication
Hardening Kafka Replication
 
Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)
 
Building a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istioBuilding a scalable microservice architecture with envoy, kubernetes and istio
Building a scalable microservice architecture with envoy, kubernetes and istio
 
Deploy Prometheus - Grafana and EFK stack on Kubic k8s Clusters
Deploy Prometheus - Grafana and EFK stack on Kubic k8s ClustersDeploy Prometheus - Grafana and EFK stack on Kubic k8s Clusters
Deploy Prometheus - Grafana and EFK stack on Kubic k8s Clusters
 
MySQL Monitoring using Prometheus & Grafana
MySQL Monitoring using Prometheus & GrafanaMySQL Monitoring using Prometheus & Grafana
MySQL Monitoring using Prometheus & Grafana
 
Monitoring with prometheus
Monitoring with prometheusMonitoring with prometheus
Monitoring with prometheus
 
Apache Airflow Architecture
Apache Airflow ArchitectureApache Airflow Architecture
Apache Airflow Architecture
 
Introduction to Apache Airflow
Introduction to Apache AirflowIntroduction to Apache Airflow
Introduction to Apache Airflow
 
Monitoring kubernetes with prometheus
Monitoring kubernetes with prometheusMonitoring kubernetes with prometheus
Monitoring kubernetes with prometheus
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
 
Airflow for Beginners
Airflow for BeginnersAirflow for Beginners
Airflow for Beginners
 
CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016] CETH for XDP [Linux Meetup Santa Clara | July 2016]
CETH for XDP [Linux Meetup Santa Clara | July 2016]
 
Testing Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with SherlockTesting Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with Sherlock
 
No data loss pipeline with apache kafka
No data loss pipeline with apache kafkaNo data loss pipeline with apache kafka
No data loss pipeline with apache kafka
 
RedisConf17- Using Redis at scale @ Twitter
RedisConf17- Using Redis at scale @ TwitterRedisConf17- Using Redis at scale @ Twitter
RedisConf17- Using Redis at scale @ Twitter
 
Dynamically Scaling Data Streams across Multiple Kafka Clusters with Zero Fli...
Dynamically Scaling Data Streams across Multiple Kafka Clusters with Zero Fli...Dynamically Scaling Data Streams across Multiple Kafka Clusters with Zero Fli...
Dynamically Scaling Data Streams across Multiple Kafka Clusters with Zero Fli...
 
Securing Kafka
Securing Kafka Securing Kafka
Securing Kafka
 
Kafka basics
Kafka basicsKafka basics
Kafka basics
 
How Uber scaled its Real Time Infrastructure to Trillion events per day
How Uber scaled its Real Time Infrastructure to Trillion events per dayHow Uber scaled its Real Time Infrastructure to Trillion events per day
How Uber scaled its Real Time Infrastructure to Trillion events per day
 

Ähnlich wie 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, 2014
Sameera Jayasoma
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
DaisyWatson5
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class Loader
Kaniska Mandal
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 

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!

Hinweis der Redaktion

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