SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
JVM Internals
How does your preferred platform works



                                           Luiz Fernando Teston
                                                       Summa

            feu.teston@gmail.com / @FeuTeston
Introduction to (J)VMs

 Mimics a Machine or OS
   Abstraction
   Security
   Isolation
   ...
Machine/OS mimics

Loads code
Executes code
Takes care of memory
Manage code for security
Machine/OS mimics

Loads code :: Classloader
Executes code
Takes care of memory :: GC
Manage code for security
Execute code. How?


Register based
Stack based
Register based

Less (byte) code
Works like your processor
More difficult to write a compiler
Easier to execute
Register based

                 getvar R1, "a"
                 getvar R2, "b"
 c = a + b
                 getvar R3, "c"
                 add R3, R1, R2
Stack based (JVM way)

More (byte) code
Works like your HP Calculator ;-)
Easier to write a compiler
Difficult to execute
Stack based
              push 'a'
              getvar
              push ‘b'
 c = a + b    getvar
              add
              push 'c'
              storevar
Java Binary Class Layout
Java Binary Class Layout
     ClassFile {
     	    u4 magic;
     	    u2 minor_version;
     	    u2 major_version;
     	    u2 constant_pool_count;
     	    cp_info constant_pool[constant_pool_count-1];
     	    u2 access_flags;
     	    u2 this_class;
     	    u2 super_class;
     	    u2 interfaces_count;
     	    u2 interfaces[interfaces_count];
     	    u2 fields_count;
     	    field_info fields[fields_count];
     	    u2 methods_count;
     	    method_info methods[methods_count];
     	    u2 attributes_count;
     	    attribute_info attributes[attributes_count];
     }
Java Binary Class Layout

     method_info {
     	    u2 access_flags;
     	    u2 name_index;
     	    u2 descriptor_index;
     	    u2 attributes_count;
     	    attribute_info attributes[attributes_count];
     }
Java Binary Class Layout
     Code_attribute {
     	   u2 attribute_name_index;
     	   u4 attribute_length;
     	   u2 max_stack;
     	   u2 max_locals;
     	   u4 code_length;
     	   u1 code[code_length];
     	   u2 exception_table_length; {	
     	   	      u2 start_pc;
     	   	      u2 end_pc;
     	   	      u2 handler_pc;
     	   	      u2 catch_type;
     	   }
     	   exception_table[exception_table_length];
     	   u2 attributes_count;
     	   attribute_info attributes[attributes_count];
     }
Sample source

public class Sample {

	 public int sum(int a, int b){
	 	 return a + b;
	 }

}
Sample bytecode
                              Compiled from "Sample.java"
                              public class Sample extends java.lang.Object{
                              public Sample();
public class Sample {          Code:
                               0:	aload_0
                               1:	invokespecial	 1; //Method java/lang/
                                                  #
	 public int sum(int a,    intObject."<init>":()V
                               b){
                               4:	return
	 	 return a + -c Sample
             javap
                   b;
	 }                           public int sum(int, int);
                               Code:
                               0:	iload_1
}                              1:	iload_2
                               2:	iadd
                               3:	ireturn

                              }
Assembly,
baby
Assembly,
baby


Yes, we have low
 level stuff too!
Manipulating JVM Assembly
Stack bytecode execution?

Here we are talking about the method’s code section
Usually it is a switch statement on the opcode
The stack grow and sink as necessary
The opcode instruction are executed consuming and
producing stack entries
Creating JVM bytecode
Java     Jasmin
Source   ASM
         Java
Jython
         Source

JRuby    Clojure


Scala    Groovy



and many others...
Creating JVM bytecode
Java     Jasmin
Source   ASM
         Java
Jython
         Source
                     compiles    0xCAFEBABE
JRuby    Clojure                      ...
                                (JVM bytecode)
Scala    Groovy



and many others...
Creating JVM bytecode
Java     Jasmin
Source   ASM
         Java
Jython
         Source
                     runtime gen    0xCAFEBABE
JRuby    Clojure                         ...
                                   (JVM bytecode)
Scala    Groovy



and many others...
Many easy ways of
extending bytecodes

Without ‘brushing bytecodes’:
  CGLib
  Java Proxies
  JavaAssist
Many easy ways of
extending bytecodes

Without ‘brushing bytecodes’:
  CGLib
  Java Proxies                  They’re easy!
  JavaAssist
Bytecodes can be...

Generated when compiling a language
Generated at runtime during class loading
Modified at runtime during class loading
Extended at runtime dynamically
Bytecodes can be...

Generated when compiling a language




                                          }
Generated at runtime during class loading
Modified at runtime during class loading
                                             JVM
Extended at runtime dynamically
                                            Feature
Loading code: Classloaders
Classloaders
Loads code in a lazy manner
Can do anything while loading code
  Create new code
  Manipulate existing code
Hierarchal
Can be isolated
Javadoc: classloaders are...
 A class loader is an object that is responsible for
 loading classes.
 Given the binary name of a class, a class loader should
 attempt to locate or generate data that constitutes a
 definition for the class.
 A typical strategy is to transform the name into a file
 name and then read a "class file" of that name from a
 file system.
How classloading
(normally) works
There’s a classloader tree
For each classloader entry:
  Search classes inside the classpath directories
  Search classes inside jar files in the classpath
Until the class definition is find, searches the child
classloaders
Fancy Classloaders



class FancyClassLoader extends ClassLoader {
   public Class findClass(String name) {
     byte[] b = compileOnTheFly(name + “.fancy”);
     return defineClass(name, b, 0, b.length);
   }
}
Fancy Classloaders
                             Easy to create,
                             extend and use!



class FancyClassLoader extends ClassLoader {
   public Class findClass(String name) {
     byte[] b = compileOnTheFly(name + “.fancy”);
     return defineClass(name, b, 0, b.length);
   }
}
Great Classloader samples

Remote Classloader (RMI)
  Think for a minute about the difficulty to build this
  without the JVM
  Loads classes using network connection
  Makes possible to put remote invocation in a next
  level
Great Classloader samples

AppServer Classloaders per application
  Can isolate AppServer classes from the hosted
  application
  Isolates classes from each application
  Makes ease to implement hotdeploy
Great Classloader samples
OSGi
  Plugin/bundle architecture with lifecycle
  Isolates plugins/bundles classes really well
  Makes possible to have many versions of the ‘same
  class’ on different bundles
  Isolate internal classes from plugin/bundle from the
  ones who needs to be exported
Great Classloader samples
AOP (runtime)
  Can implement AOP on the fly (runtime)
  Many applications:
    Transaction management
    Logging
    Error tracing
Where the garbage
cames from?
How to manage memory?

C
    malloc/free
C++
    new/delete
How to manage memory?



                  }
C
    malloc/free
                      Almost the same...
C++
    new/delete
Memory fragmentation
Memory as a big byte array...
m[0], m[1] ..... m[MAX]
Memory fragmentation
Memory as a big byte array...
m[0], m[1] ..... m[MAX]

     x




         *x = 1, sizeof(x_type) = 2
Memory fragmentation
Memory as a big byte array...
m[0], m[1] ..... m[MAX]

     x        y




         *x = 1, sizeof(x_type) = 2
         *y = 1, sizeof(y_type) = 1
Memory fragmentation
Memory as a big byte array...
m[0], m[1] ..... m[MAX]

     x        y             z




         *x = 1, sizeof(x_type) = 2
         *y = 1, sizeof(y_type) = 1
         *z = 1, sizeof(z_type) = 6
Memory fragmentation
Memory as a big byte array...
m[0], m[1] ..... m[MAX]

     x        y                z

Each item is a index + size.
‘Mallocked’ by C’s runtime.
         *x = 1, sizeof(x_type) = 2
         *y = 1, sizeof(y_type) = 1
         *z = 1, sizeof(z_type) = 6
Memory fragmentation
Memory as a big byte array...
                 WARNING!
m[0], m[1] ..... m[MAX]
            Easy to mess with
      x         y               z
            Easy to fragment
Each itemEasy to forgot leaks in long runs
          is a index + size.
‘Mallocked’ by C’s runtime.
          *x = 1, sizeof(x_type) = 2
          *y = 1, sizeof(y_type) = 1
          *z = 1, sizeof(z_type) = 6
Garbage Collection

   Possible solution for memory
   fragmentation
   Memory is no longer managed by
   programmer
   Runtime takes care of fragmentation
   during garbage collecting
How GC works?

  From time to time it searches from unused
  memory
  When it find unused memory, it cleans it and it
  could defragmentize it
  Behavior defined by JVM runtime options + JVM
  implementation
How GC works?
  Parameters includes:
    Running in parallel
    Intervals per region
    Specifying memory sizes for each type of
    object
      eden
      survivor1, survivor 2
      PermGen
Sample GC-ed environment
    eden      x   y   z


 survivor 1   a   b   c



survivor 2    w   k   l
Sample GC-ed environment
    eden      x   y   z


 survivor 1   a   b   c



survivor 2    w   k   l
Sample GC-ed environment
    eden      x       z


 survivor 1   a   b



survivor 2        k   l
Sample GC-ed environment
    eden     x        z


 survivor 1 a b


survivor 2   k    l
GC in practice
Mark and sweep
GC in practice
Mark and sweep
GC in practice
Mark and sweep
GC in practice
Mark and sweep
GC in practice
Copying GC
GC in practice
Copying GC
GC in practice
Copying GC
GC in practice
Copying GC

          Copy
GC in practice
Copying GC
GC in practice
Copying GC
Questions? Thanks!




      feu.teston@gmail.com / @FeuTeston
References on the web
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html

http://java.sun.com/developer/technicalArticles/Networking/classloaders/
http://blog.osgi.org/2011/05/what-you-should-know-about-class.html

http://www.theserverside.com/news/1364680/Understanding-J2EE-Application-Server-ClassLoading-
Architectures

http://www.sidhe.org/~dan/blog/archives/000189.html
http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/

http://download.oracle.com/otndocs/jcp/jcfsu-0.1-prc-oth-JSpec/
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11

http://asm.ow2.org/doc/tutorial-asm-2.0.html
http://stackoverflow.com/questions/2129044/java-heap-terminology-young-old-and-permanent-generations

http://javarevisited.blogspot.com.br/2011/04/garbage-collection-in-java.html
http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html

http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

Weitere ähnliche Inhalte

Was ist angesagt?

Using Flame Graphs
Using Flame GraphsUsing Flame Graphs
Using Flame GraphsIsuru Perera
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292ytoshima
 
Threads and Java Memory Model Explained
Threads and Java Memory Model ExplainedThreads and Java Memory Model Explained
Threads and Java Memory Model ExplainedLuiz Fernando Teston
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMKris Mok
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, UkraineVladimir Ivanov
 
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyYusuke Yamamoto
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013Vladimir Ivanov
 
Software Profiling: Understanding Java Performance and how to profile in Java
Software Profiling: Understanding Java Performance and how to profile in JavaSoftware Profiling: Understanding Java Performance and how to profile in Java
Software Profiling: Understanding Java Performance and how to profile in JavaIsuru Perera
 
State of the art - server side JavaScript - web-5 2012
State of the art - server side JavaScript - web-5 2012State of the art - server side JavaScript - web-5 2012
State of the art - server side JavaScript - web-5 2012Alexandre Morgaut
 
Java Performance & Profiling
Java Performance & ProfilingJava Performance & Profiling
Java Performance & ProfilingIsuru Perera
 
JVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesJVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesKris Mok
 
Size of in java
Size of in javaSize of in java
Size of in javalorban
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Hyuk Hur
 
A New Age of JVM Garbage Collectors (Clojure Conj 2019)
A New Age of JVM Garbage Collectors (Clojure Conj 2019)A New Age of JVM Garbage Collectors (Clojure Conj 2019)
A New Age of JVM Garbage Collectors (Clojure Conj 2019)Alexander Yakushev
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptTimur Shemsedinov
 
Software Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsSoftware Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsIsuru Perera
 

Was ist angesagt? (20)

Using Flame Graphs
Using Flame GraphsUsing Flame Graphs
Using Flame Graphs
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292
 
Threads and Java Memory Model Explained
Threads and Java Memory Model ExplainedThreads and Java Memory Model Explained
Threads and Java Memory Model Explained
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VM
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
 
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudyスローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
スローダウン、ハングを一発解決 スレッドダンプはトラブルシューティングの味方 #wlstudy
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
 
Software Profiling: Understanding Java Performance and how to profile in Java
Software Profiling: Understanding Java Performance and how to profile in JavaSoftware Profiling: Understanding Java Performance and how to profile in Java
Software Profiling: Understanding Java Performance and how to profile in Java
 
State of the art - server side JavaScript - web-5 2012
State of the art - server side JavaScript - web-5 2012State of the art - server side JavaScript - web-5 2012
State of the art - server side JavaScript - web-5 2012
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
Java Performance & Profiling
Java Performance & ProfilingJava Performance & Profiling
Java Performance & Profiling
 
JVM: A Platform for Multiple Languages
JVM: A Platform for Multiple LanguagesJVM: A Platform for Multiple Languages
JVM: A Platform for Multiple Languages
 
Size of in java
Size of in javaSize of in java
Size of in java
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"
 
A New Age of JVM Garbage Collectors (Clojure Conj 2019)
A New Age of JVM Garbage Collectors (Clojure Conj 2019)A New Age of JVM Garbage Collectors (Clojure Conj 2019)
A New Age of JVM Garbage Collectors (Clojure Conj 2019)
 
Shark
Shark Shark
Shark
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
Java in flames
Java in flamesJava in flames
Java in flames
 
Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScript
 
Software Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and FlamegraphsSoftware Profiling: Java Performance, Profiling and Flamegraphs
Software Profiling: Java Performance, Profiling and Flamegraphs
 

Andere mochten auch

Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Doug Hawkins
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecturesubnesh
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data ScienceNiko Vuokko
 
Introduction to Data Science and Analytics
Introduction to Data Science and AnalyticsIntroduction to Data Science and Analytics
Introduction to Data Science and AnalyticsSrinath Perera
 
Introduction on Data Science
Introduction on Data ScienceIntroduction on Data Science
Introduction on Data ScienceEdureka!
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Marcos García
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Svetlin Nakov
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data ScienceANOOP V S
 
How to Become a Data Scientist
How to Become a Data ScientistHow to Become a Data Scientist
How to Become a Data Scientistryanorban
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineChun-Yu Wang
 
Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Big Data [sorry] & Data Science: What Does a Data Scientist Do?Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Big Data [sorry] & Data Science: What Does a Data Scientist Do?Data Science London
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkVolker Hirsch
 

Andere mochten auch (15)

3. jvm
3. jvm3. jvm
3. jvm
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011
 
Java Virtual Machine - Internal Architecture
Java Virtual Machine - Internal ArchitectureJava Virtual Machine - Internal Architecture
Java Virtual Machine - Internal Architecture
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Introduction to Data Science and Analytics
Introduction to Data Science and AnalyticsIntroduction to Data Science and Analytics
Introduction to Data Science and Analytics
 
Introduction on Data Science
Introduction on Data ScienceIntroduction on Data Science
Introduction on Data Science
 
Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)Quick introduction to Java Garbage Collector (JVM GC)
Quick introduction to Java Garbage Collector (JVM GC)
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Introduction to Data Science by Datalent Team @Data Science Clinic #9
Introduction to Data Science by Datalent Team @Data Science Clinic #9Introduction to Data Science by Datalent Team @Data Science Clinic #9
Introduction to Data Science by Datalent Team @Data Science Clinic #9
 
How to Become a Data Scientist
How to Become a Data ScientistHow to Become a Data Scientist
How to Become a Data Scientist
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 
Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Big Data [sorry] & Data Science: What Does a Data Scientist Do?Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Big Data [sorry] & Data Science: What Does a Data Scientist Do?
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
 

Ähnlich wie Jvm internals

Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHoward Lewis Ship
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topicsRajesh Verma
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slidesunny khan
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiasanjeeviniindia1186
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jniPeter Hagemeyer
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...chen yuki
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 

Ähnlich wie Jvm internals (20)

Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
FTD JVM Internals
FTD JVM InternalsFTD JVM Internals
FTD JVM Internals
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 

Kürzlich hochgeladen

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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
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
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
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
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Kürzlich hochgeladen (20)

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?
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
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)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
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
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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
 
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
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Jvm internals

  • 1. JVM Internals How does your preferred platform works Luiz Fernando Teston Summa feu.teston@gmail.com / @FeuTeston
  • 2. Introduction to (J)VMs Mimics a Machine or OS Abstraction Security Isolation ...
  • 3. Machine/OS mimics Loads code Executes code Takes care of memory Manage code for security
  • 4. Machine/OS mimics Loads code :: Classloader Executes code Takes care of memory :: GC Manage code for security
  • 5. Execute code. How? Register based Stack based
  • 6. Register based Less (byte) code Works like your processor More difficult to write a compiler Easier to execute
  • 7. Register based getvar R1, "a" getvar R2, "b" c = a + b getvar R3, "c" add R3, R1, R2
  • 8. Stack based (JVM way) More (byte) code Works like your HP Calculator ;-) Easier to write a compiler Difficult to execute
  • 9. Stack based push 'a' getvar push ‘b' c = a + b getvar add push 'c' storevar
  • 11. Java Binary Class Layout ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_info fields[fields_count]; u2 methods_count; method_info methods[methods_count]; u2 attributes_count; attribute_info attributes[attributes_count]; }
  • 12. Java Binary Class Layout method_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; }
  • 13. Java Binary Class Layout Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 catch_type; } exception_table[exception_table_length]; u2 attributes_count; attribute_info attributes[attributes_count]; }
  • 14. Sample source public class Sample { public int sum(int a, int b){ return a + b; } }
  • 15. Sample bytecode Compiled from "Sample.java" public class Sample extends java.lang.Object{ public Sample(); public class Sample { Code: 0: aload_0 1: invokespecial 1; //Method java/lang/ # public int sum(int a, intObject."<init>":()V b){ 4: return return a + -c Sample javap b; } public int sum(int, int); Code: 0: iload_1 } 1: iload_2 2: iadd 3: ireturn }
  • 17. Assembly, baby Yes, we have low level stuff too!
  • 19. Stack bytecode execution? Here we are talking about the method’s code section Usually it is a switch statement on the opcode The stack grow and sink as necessary The opcode instruction are executed consuming and producing stack entries
  • 20. Creating JVM bytecode Java Jasmin Source ASM Java Jython Source JRuby Clojure Scala Groovy and many others...
  • 21. Creating JVM bytecode Java Jasmin Source ASM Java Jython Source compiles 0xCAFEBABE JRuby Clojure ... (JVM bytecode) Scala Groovy and many others...
  • 22. Creating JVM bytecode Java Jasmin Source ASM Java Jython Source runtime gen 0xCAFEBABE JRuby Clojure ... (JVM bytecode) Scala Groovy and many others...
  • 23. Many easy ways of extending bytecodes Without ‘brushing bytecodes’: CGLib Java Proxies JavaAssist
  • 24. Many easy ways of extending bytecodes Without ‘brushing bytecodes’: CGLib Java Proxies They’re easy! JavaAssist
  • 25. Bytecodes can be... Generated when compiling a language Generated at runtime during class loading Modified at runtime during class loading Extended at runtime dynamically
  • 26. Bytecodes can be... Generated when compiling a language } Generated at runtime during class loading Modified at runtime during class loading JVM Extended at runtime dynamically Feature
  • 28. Classloaders Loads code in a lazy manner Can do anything while loading code Create new code Manipulate existing code Hierarchal Can be isolated
  • 29. Javadoc: classloaders are... A class loader is an object that is responsible for loading classes. Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.
  • 30. How classloading (normally) works There’s a classloader tree For each classloader entry: Search classes inside the classpath directories Search classes inside jar files in the classpath Until the class definition is find, searches the child classloaders
  • 31. Fancy Classloaders class FancyClassLoader extends ClassLoader { public Class findClass(String name) { byte[] b = compileOnTheFly(name + “.fancy”); return defineClass(name, b, 0, b.length); } }
  • 32. Fancy Classloaders Easy to create, extend and use! class FancyClassLoader extends ClassLoader { public Class findClass(String name) { byte[] b = compileOnTheFly(name + “.fancy”); return defineClass(name, b, 0, b.length); } }
  • 33. Great Classloader samples Remote Classloader (RMI) Think for a minute about the difficulty to build this without the JVM Loads classes using network connection Makes possible to put remote invocation in a next level
  • 34. Great Classloader samples AppServer Classloaders per application Can isolate AppServer classes from the hosted application Isolates classes from each application Makes ease to implement hotdeploy
  • 35. Great Classloader samples OSGi Plugin/bundle architecture with lifecycle Isolates plugins/bundles classes really well Makes possible to have many versions of the ‘same class’ on different bundles Isolate internal classes from plugin/bundle from the ones who needs to be exported
  • 36. Great Classloader samples AOP (runtime) Can implement AOP on the fly (runtime) Many applications: Transaction management Logging Error tracing
  • 38. How to manage memory? C malloc/free C++ new/delete
  • 39. How to manage memory? } C malloc/free Almost the same... C++ new/delete
  • 40. Memory fragmentation Memory as a big byte array... m[0], m[1] ..... m[MAX]
  • 41. Memory fragmentation Memory as a big byte array... m[0], m[1] ..... m[MAX] x *x = 1, sizeof(x_type) = 2
  • 42. Memory fragmentation Memory as a big byte array... m[0], m[1] ..... m[MAX] x y *x = 1, sizeof(x_type) = 2 *y = 1, sizeof(y_type) = 1
  • 43. Memory fragmentation Memory as a big byte array... m[0], m[1] ..... m[MAX] x y z *x = 1, sizeof(x_type) = 2 *y = 1, sizeof(y_type) = 1 *z = 1, sizeof(z_type) = 6
  • 44. Memory fragmentation Memory as a big byte array... m[0], m[1] ..... m[MAX] x y z Each item is a index + size. ‘Mallocked’ by C’s runtime. *x = 1, sizeof(x_type) = 2 *y = 1, sizeof(y_type) = 1 *z = 1, sizeof(z_type) = 6
  • 45. Memory fragmentation Memory as a big byte array... WARNING! m[0], m[1] ..... m[MAX] Easy to mess with x y z Easy to fragment Each itemEasy to forgot leaks in long runs is a index + size. ‘Mallocked’ by C’s runtime. *x = 1, sizeof(x_type) = 2 *y = 1, sizeof(y_type) = 1 *z = 1, sizeof(z_type) = 6
  • 46. Garbage Collection Possible solution for memory fragmentation Memory is no longer managed by programmer Runtime takes care of fragmentation during garbage collecting
  • 47. How GC works? From time to time it searches from unused memory When it find unused memory, it cleans it and it could defragmentize it Behavior defined by JVM runtime options + JVM implementation
  • 48. How GC works? Parameters includes: Running in parallel Intervals per region Specifying memory sizes for each type of object eden survivor1, survivor 2 PermGen
  • 49. Sample GC-ed environment eden x y z survivor 1 a b c survivor 2 w k l
  • 50. Sample GC-ed environment eden x y z survivor 1 a b c survivor 2 w k l
  • 51. Sample GC-ed environment eden x z survivor 1 a b survivor 2 k l
  • 52. Sample GC-ed environment eden x z survivor 1 a b survivor 2 k l
  • 53. GC in practice Mark and sweep
  • 54. GC in practice Mark and sweep
  • 55. GC in practice Mark and sweep
  • 56. GC in practice Mark and sweep
  • 63. Questions? Thanks! feu.teston@gmail.com / @FeuTeston
  • 64. References on the web http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html http://java.sun.com/developer/technicalArticles/Networking/classloaders/ http://blog.osgi.org/2011/05/what-you-should-know-about-class.html http://www.theserverside.com/news/1364680/Understanding-J2EE-Application-Server-ClassLoading- Architectures http://www.sidhe.org/~dan/blog/archives/000189.html http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/ http://download.oracle.com/otndocs/jcp/jcfsu-0.1-prc-oth-JSpec/ http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11 http://asm.ow2.org/doc/tutorial-asm-2.0.html http://stackoverflow.com/questions/2129044/java-heap-terminology-young-old-and-permanent-generations http://javarevisited.blogspot.com.br/2011/04/garbage-collection-in-java.html http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html