SlideShare a Scribd company logo
1 of 32
Download to read offline
Java Runtime:
повседневные обязанности JVM


Андрей Паньгин
ведущий разработчик
проекта Одноклассники
JVM Iceberg




              1
JVM Iceberg




              2
Launcher
  • java.exe – just a simple C program
     1.   Locate JRE
     2.   Select version
     3.   Parse arguments
     4.   JNI_CreateJavaVM
     5.   JNIEnv::FindClass
     6.   JNIEnv::GetStaticMethodID (main)
     7.   JNIEnv::CallStaticVoidMethod




                                             3
Other launchers
  • Differ only by Main Class
     –   javac       com.sun.tools.javac.Main
     –   javadoc     com.sun.tools.javadoc.Main
     –   javah       com.sun.tools.javah.Main
     –   jconsole    sun.tools.jconsole.JConsole
     –   jmap        sun.tools.jmap.JMap
     –   …
  • Even -version calls Java
     – sun.misc.Version.print()


                                                   4
Class loading
   • Class loading != Class initialization
   • ClassLoader prepares byte[] definition
   • Real loading is done inside VM
      – ClassLoader.defineClass0
      – Parses, verifies and creates internal VM structures


   • Unreferenced classes may be unloaded
      – -XX:+CMSClassUnloadingEnabled



                                                              5
Class Metadata
  • Constant Pool, Interfaces, Methods, Fields
  • Exceptions, Annotations, vtables, itables

  • Java 8: PermGen  Metaspace
     – java.lang.OutOfMemoryError: PermGen space
  • Field reordering
     – -XX:+CompactFields, -XX:FieldsAllocationStyle=1




                                                         6
Class data sharing
   • Snapshot of commonly used classes
      – jre/lib/classlist
   • Mapped into memory directly from disk
      – classes.jsa
   • Shared between multiple JVM instances
   • Improves start-up time, reduces footprint
      – -XX:+UseSharedSpaces
      – -XX:+DumpSharedSpaces



                                                 7
Bytecode verification
  • Java 6 Split Verifier
     – Inferencing verifier (javac) + Type checking (run-time)
     – StackMapTable attribute in .class
  • Skip verification
     – -XX:-BytecodeVerificationRemote
     – -XX:-BytecodeVerificationLocal
     – Inherit sun.reflect.MagicAccessorImpl




                                                                 8
Class initialization
   • When?
   • 12-step procedure described in JLS §12.4
   • Basically, the invocation of <clinit>
     (static initializer)




                                                9
Bytecodes
  • Stack machine
  • 203 Java bytecodes
     Stack manipulation   iconst, fconst, bipush, pop, dup, swap
     Type conversion      i2l, f2i, l2d
     Arithmetic / logic   iadd, isub, imul, ixor, ishr
     Local variables      iload, aload, istore, fstore
     Arrays               iaload, aaload, iastore, aastore, arraylength
     Fields               getfield, putfield, getstatic, putstatic
     Branches             ifeq, ifgt, goto, tableswitch, lookupswitch
     Method calls         invokevirtual, invokeinterface, invokestatic, return
     Allocation           new, anewarray, multianewarray
     Other                monitorenter, monitorexit, instanceof, athrow

                                                                                 10
JVM specific bytecodes
  • fast_igetfield, fast_iputfield
     – -XX:+RewriteBytecodes
  • fast_iload2, fast_aaccess_0
     – -XX:+RewriteFrequentPairs
  • fast_binaryswitch
  • return_register_finalizer




                                     11
Bytecode interpreter
  • C++ and Assembler (template) interpreter
  • Generated at VM start-up
  • Run-time code profiling
     – -XX:CompileThreshold=10000
  • Run-time CP resolution and bytecode rewriting
  • Optimizations
     – Dispatch table, top-of-stack caching




                                                    12
Stack
  • Java (expression) vs. Native (execution)
     – -XX:ThreadStackSize=320
  • Guard pages
                                               Empty
     – -XX:StackShadowPages=20
     – -XX:StackYellowPages=2
                                               Shadow
     – -XX:StackRedPages=1
                                               Frame
                                               Frame
                                               Frame



                                                        13
Stack frame   SP   Expression
                     stack

                    Monitors
                     Method
                      old SP
              FP      old FP
                   Return addr
                     Locals


                   Expression
                     stack
                    Previous
                     frame


                                 14
Frame types
  • Interpreted, Compiled, Native
     – Different layout
  • Inlining
     – 1 frame for multiple nested methods
  • Deoptimization
     – When optimistic assumptions fail
     – (exceptions, class hierarchy changes etc.)




                                                    15
Threads
  • Java threads & VM threads
  • States: in_java, in_vm, in_native, blocked
  • Thread pointer in register
     – Fast Thread.currentThread()
  • Priority policy (0 – normal, 1 – aggressive)
     – -XX:ThreadPriorityPolicy=N
  • TLAB allocation
     – -XX:+UseTLAB, -XX:TLABSize=0


                                                   16
Synchronization
  • Simple uncontended lock – CAS
  • Biased locking
     –   -XX:+UseBiasedLocking
     –   -XX:BiasedLockingStartupDelay=4000
     –   -XX:BiasedLockingBulkRebiasThreshold=20
     –   -XX:BiasedLockingBulkRevokeThreshold=40
  • Contended lock optimizations
     – Spin  Yield  Park



                                                   17
Java-level locks
   • java.util.concurrent.locks.LockSupport
   • park() / unpark()
   • OS-level primitives
      – Mutex + Condition variable




                                              18
wait / notify
   • What’s wrong with this code?
     void waitForCompletion() {   void setCompleted() {
       synchronized (lock) {        synchronized (lock) {
         if (!completed) {            completed = true;
             lock.wait();             lock.notifyAll();
         }                          }
       }                          }
     }




                                                            19
wait / notify
   • What’s wrong with this code?
     void waitForCompletion() {   void setCompleted() {
       synchronized (lock) {        synchronized (lock) {
         if (!completed) {            completed = true;
             lock.wait();             lock.notifyAll();
         }                          }
       }                          }
     }


   • -XX:+FilterSpuriousWakeups



                                                            20
Object header
   Unlocked
       unused              hashCode       0   age   0 01
                                                           Monitor
   Thin lock
                   Displaced header ptr               00

   Inflated lock
                     Inflated lock ptr                10
                                                           Stack
   Biased lock
           JavaThread              epoch 0    age   1 01




                                                                     21
Safepoints
  • When?
     –   GC phases
     –   Thread dump
     –   Deoptimization
     –   Revoke/rebias BiasedLock
  • How?
     – Interpreted: switch dispatch table
     – Compiled: page polling
     – Native: on return and on JNI calls
  • -XX:+PrintSafepointStatistics


                                            22
Native methods
  • System.loadLibrary()
  • Lazy linking
  • Expensive invocation
     1.   Create stack frame
     2.   Set up arguments according to native calling convention
     3.   Pass JNIEnv* and jclass
     4.   Lock / unlock if synchronized
     5.   Trace method entry / method exit
     6.   Check for safepoint
     7.   Check exceptions


                                                                    23
JNI functions
   •   Executed in VM context
   •   Check for safepoint
   •   jobject == index in thread-local JNIHandles array
   •   Optional verification
       – -XX:+CheckJNICalls




                                                           24
Exceptions
    • Which code is faster?
 for (;;) {                      try {
   int index = getNextIndex();     for (;;) {
   if (index >= arr.length) {        int index = getNextIndex();
     break;                          sum += arr[index];
   }                               }
   sum += array[index];          } catch (IndexOutOfBoundsException e) {
 }                                 // break
                                 }




                                                                           25
Exceptions
    • Which code is faster?
 for (;;) {                         try {
   int index = getNextIndex();        for (;;) {
   if (index >= arr.length) {           int index = getNextIndex();
     break;                             sum += arr[index];
   }                                  }
   sum += array[index];             } catch (IndexOutOfBoundsException e) {
 }                                    // break
                                    }

    • try-catch is free (exception tables)
    • throw is expensive
      (find handler, unwind stack, release locks, build stack trace)

                                                                              26
Reflection
  • getDeclaredFields(), getDeclaredMethods()
     – VM Internal structures  Java representation
  • Field getters and setters
     – sun.misc.Unsafe
  • Method.invoke()
     1.   Native implementation
     2.   Dynamic bytecode generation (up to 10x faster)
          -Dsun.reflect.inflationThreshold=15



                                                           27
MethodAccessor example
  • void Point.move(float x, float y, boolean relative);
     class PointMove_MethodAccessor implements MethodAccessor {

         public Object invoke(Object target, Object[] args) {
           float x = ((Float) args[0]).floatValue();
           float y = ((Float) args[1]).floatValue();
           boolean relative = ((Boolean) args[2]).booleanValue();

             try {
               ((Point) target).move(x, y, relative);
             } catch (Throwable t) {
               throw new InvocationTargetException(t);
             }

             return null;
         }
     }
                                                                    28
Troubleshooting
  • Signal handler (SIGSEGV, SIGILL, SIGFPE…)
  • Not all SEGV are fatal
     – Polling page
     – Implicit NullPointerException, StackOverflowError
  • hs_err.log
     – Threads, Stack frames, Memory map
     – Registers, Top of stack, Instructions
     – -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly



                                                           29
Still much to learn




                      30
Thank you!
  • OpenJDK sources
    – http://hg.openjdk.java.net
  • Contacts
    – andrey.pangin@odnoklassniki.ru
  • Open Source @ Odnoklassniki
    – https://github.com/odnoklassniki
  • Career @ Odnoklassniki
    – http://v.ok.ru



                                         31

More Related Content

What's hot

Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
Jerry Chan
 
Bh ad-12-stealing-from-thieves-saher-slides
Bh ad-12-stealing-from-thieves-saher-slidesBh ad-12-stealing-from-thieves-saher-slides
Bh ad-12-stealing-from-thieves-saher-slides
Matt Kocubinski
 

What's hot (19)

Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumps
 
How to cook lettuce @Java casual
How to cook lettuce @Java casualHow to cook lettuce @Java casual
How to cook lettuce @Java casual
 
BlueHat v18 || A mitigation for kernel toctou vulnerabilities
BlueHat v18 || A mitigation for kernel toctou vulnerabilitiesBlueHat v18 || A mitigation for kernel toctou vulnerabilities
BlueHat v18 || A mitigation for kernel toctou vulnerabilities
 
De Java 8 a Java 17
De Java 8 a Java 17De Java 8 a Java 17
De Java 8 a Java 17
 
HandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQLHandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQL
 
Explore the history, versions and features of Java- a report by Pranav Mishra
Explore the history, versions and features of Java- a report by Pranav MishraExplore the history, versions and features of Java- a report by Pranav Mishra
Explore the history, versions and features of Java- a report by Pranav Mishra
 
De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14
 
Thread dump troubleshooting
Thread dump troubleshootingThread dump troubleshooting
Thread dump troubleshooting
 
BlueHat v18 || Hardening hyper-v through offensive security research
BlueHat v18 || Hardening hyper-v through offensive security researchBlueHat v18 || Hardening hyper-v through offensive security research
BlueHat v18 || Hardening hyper-v through offensive security research
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Application
 
jcmd #javacasual
jcmd #javacasualjcmd #javacasual
jcmd #javacasual
 
pg / shardman: шардинг в PostgreSQL на основе postgres / fdw, pg / pathman и ...
pg / shardman: шардинг в PostgreSQL на основе postgres / fdw, pg / pathman и ...pg / shardman: шардинг в PostgreSQL на основе postgres / fdw, pg / pathman и ...
pg / shardman: шардинг в PostgreSQL на основе postgres / fdw, pg / pathman и ...
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
 
Vitess 解析
Vitess 解析Vitess 解析
Vitess 解析
 
Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018 Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018
 
Bh ad-12-stealing-from-thieves-saher-slides
Bh ad-12-stealing-from-thieves-saher-slidesBh ad-12-stealing-from-thieves-saher-slides
Bh ad-12-stealing-from-thieves-saher-slides
 
How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
 
Мастер-класс "Логическая репликация и Avito" / Константин Евтеев, Михаил Тюр...
Мастер-класс "Логическая репликация и Avito" / Константин Евтеев,  Михаил Тюр...Мастер-класс "Логическая репликация и Avito" / Константин Евтеев,  Михаил Тюр...
Мастер-класс "Логическая репликация и Avito" / Константин Евтеев, Михаил Тюр...
 
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
 

Similar to Java Runtime: повседневные обязанности JVM

JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
"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
Vladimir Ivanov
 
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Efficient Bytecode Analysis: Linespeed Shellcode DetectionEfficient Bytecode Analysis: Linespeed Shellcode Detection
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Georg Wicherski
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 
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
Vladimir Ivanov
 

Similar to Java Runtime: повседневные обязанности JVM (20)

JVM Under the Hood
JVM Under the HoodJVM Under the Hood
JVM Under the Hood
 
Lifecycle of a JIT compiled code
Lifecycle of a JIT compiled codeLifecycle of a JIT compiled code
Lifecycle of a JIT compiled code
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java Applications
 
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...
 
Java Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey KovalenkoJava Jit. Compilation and optimization by Andrey Kovalenko
Java Jit. Compilation and optimization by Andrey Kovalenko
 
"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
 
New hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdfNew hope is comming? Project Loom.pdf
New hope is comming? Project Loom.pdf
 
Efficient Bytecode Analysis: Linespeed Shellcode Detection
Efficient Bytecode Analysis: Linespeed Shellcode DetectionEfficient Bytecode Analysis: Linespeed Shellcode Detection
Efficient Bytecode Analysis: Linespeed Shellcode Detection
 
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
 
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
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Eclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JITEclipse Day India 2015 - Java bytecode analysis and JIT
Eclipse Day India 2015 - Java bytecode analysis and JIT
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java Bytecode
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
Java On Speed
Java On SpeedJava On Speed
Java On Speed
 

More from odnoklassniki.ru

Тестирование аварий. Андрей Губа. Highload++ 2015
Тестирование аварий. Андрей Губа. Highload++ 2015Тестирование аварий. Андрей Губа. Highload++ 2015
Тестирование аварий. Андрей Губа. Highload++ 2015
odnoklassniki.ru
 
Кадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
Кадры решают все, или стриминг видео в «Одноклассниках». Александр ТобольКадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
Кадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
odnoklassniki.ru
 
За гранью NoSQL: NewSQL на Cassandra
За гранью NoSQL: NewSQL на CassandraЗа гранью NoSQL: NewSQL на Cassandra
За гранью NoSQL: NewSQL на Cassandra
odnoklassniki.ru
 
Платформа для видео сроком в квартал. Александр Тоболь.
Платформа для видео сроком в квартал. Александр Тоболь.Платформа для видео сроком в квартал. Александр Тоболь.
Платформа для видео сроком в квартал. Александр Тоболь.
odnoklassniki.ru
 
Cистема внутренней статистики Odnoklassniki.ru
Cистема внутренней статистики Odnoklassniki.ruCистема внутренней статистики Odnoklassniki.ru
Cистема внутренней статистики Odnoklassniki.ru
odnoklassniki.ru
 
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
odnoklassniki.ru
 

More from odnoklassniki.ru (13)

Тестирование аварий. Андрей Губа. Highload++ 2015
Тестирование аварий. Андрей Губа. Highload++ 2015Тестирование аварий. Андрей Губа. Highload++ 2015
Тестирование аварий. Андрей Губа. Highload++ 2015
 
Тюним память и сетевой стек в Linux: история перевода высоконагруженных серве...
Тюним память и сетевой стек в Linux: история перевода высоконагруженных серве...Тюним память и сетевой стек в Linux: история перевода высоконагруженных серве...
Тюним память и сетевой стек в Linux: история перевода высоконагруженных серве...
 
Распределенные системы в Одноклассниках
Распределенные системы в ОдноклассникахРаспределенные системы в Одноклассниках
Распределенные системы в Одноклассниках
 
Кадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
Кадры решают все, или стриминг видео в «Одноклассниках». Александр ТобольКадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
Кадры решают все, или стриминг видео в «Одноклассниках». Александр Тоболь
 
За гранью NoSQL: NewSQL на Cassandra
За гранью NoSQL: NewSQL на CassandraЗа гранью NoSQL: NewSQL на Cassandra
За гранью NoSQL: NewSQL на Cassandra
 
Платформа для видео сроком в квартал. Александр Тоболь.
Платформа для видео сроком в квартал. Александр Тоболь.Платформа для видео сроком в квартал. Александр Тоболь.
Платформа для видео сроком в квартал. Александр Тоболь.
 
Франкенштейнизация Voldemort или key-value данные в Одноклассниках. Роман Ан...
Франкенштейнизация Voldemort или key-value данные в Одноклассниках. Роман Ан...Франкенштейнизация Voldemort или key-value данные в Одноклассниках. Роман Ан...
Франкенштейнизация Voldemort или key-value данные в Одноклассниках. Роман Ан...
 
Аварийный дамп – чёрный ящик упавшей JVM. Андрей Паньгин
Аварийный дамп – чёрный ящик упавшей JVM. Андрей ПаньгинАварийный дамп – чёрный ящик упавшей JVM. Андрей Паньгин
Аварийный дамп – чёрный ящик упавшей JVM. Андрей Паньгин
 
Управление тысячами серверов в Одноклассниках. Алексей Чудов.
Управление тысячами серверов в Одноклассниках. Алексей Чудов.Управление тысячами серверов в Одноклассниках. Алексей Чудов.
Управление тысячами серверов в Одноклассниках. Алексей Чудов.
 
Класс!ная Cassandra
Класс!ная CassandraКласс!ная Cassandra
Класс!ная Cassandra
 
Незаурядная Java как инструмент разработки высоконагруженного сервера
Незаурядная Java как инструмент разработки высоконагруженного сервераНезаурядная Java как инструмент разработки высоконагруженного сервера
Незаурядная Java как инструмент разработки высоконагруженного сервера
 
Cистема внутренней статистики Odnoklassniki.ru
Cистема внутренней статистики Odnoklassniki.ruCистема внутренней статистики Odnoklassniki.ru
Cистема внутренней статистики Odnoklassniki.ru
 
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
Как, используя Lucene, построить высоконагруженную систему поиска разнородных...
 

Recently uploaded

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

Recently uploaded (20)

+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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Java Runtime: повседневные обязанности JVM

  • 1. Java Runtime: повседневные обязанности JVM Андрей Паньгин ведущий разработчик проекта Одноклассники
  • 4. Launcher • java.exe – just a simple C program 1. Locate JRE 2. Select version 3. Parse arguments 4. JNI_CreateJavaVM 5. JNIEnv::FindClass 6. JNIEnv::GetStaticMethodID (main) 7. JNIEnv::CallStaticVoidMethod 3
  • 5. Other launchers • Differ only by Main Class – javac com.sun.tools.javac.Main – javadoc com.sun.tools.javadoc.Main – javah com.sun.tools.javah.Main – jconsole sun.tools.jconsole.JConsole – jmap sun.tools.jmap.JMap – … • Even -version calls Java – sun.misc.Version.print() 4
  • 6. Class loading • Class loading != Class initialization • ClassLoader prepares byte[] definition • Real loading is done inside VM – ClassLoader.defineClass0 – Parses, verifies and creates internal VM structures • Unreferenced classes may be unloaded – -XX:+CMSClassUnloadingEnabled 5
  • 7. Class Metadata • Constant Pool, Interfaces, Methods, Fields • Exceptions, Annotations, vtables, itables • Java 8: PermGen  Metaspace – java.lang.OutOfMemoryError: PermGen space • Field reordering – -XX:+CompactFields, -XX:FieldsAllocationStyle=1 6
  • 8. Class data sharing • Snapshot of commonly used classes – jre/lib/classlist • Mapped into memory directly from disk – classes.jsa • Shared between multiple JVM instances • Improves start-up time, reduces footprint – -XX:+UseSharedSpaces – -XX:+DumpSharedSpaces 7
  • 9. Bytecode verification • Java 6 Split Verifier – Inferencing verifier (javac) + Type checking (run-time) – StackMapTable attribute in .class • Skip verification – -XX:-BytecodeVerificationRemote – -XX:-BytecodeVerificationLocal – Inherit sun.reflect.MagicAccessorImpl 8
  • 10. Class initialization • When? • 12-step procedure described in JLS §12.4 • Basically, the invocation of <clinit> (static initializer) 9
  • 11. Bytecodes • Stack machine • 203 Java bytecodes Stack manipulation iconst, fconst, bipush, pop, dup, swap Type conversion i2l, f2i, l2d Arithmetic / logic iadd, isub, imul, ixor, ishr Local variables iload, aload, istore, fstore Arrays iaload, aaload, iastore, aastore, arraylength Fields getfield, putfield, getstatic, putstatic Branches ifeq, ifgt, goto, tableswitch, lookupswitch Method calls invokevirtual, invokeinterface, invokestatic, return Allocation new, anewarray, multianewarray Other monitorenter, monitorexit, instanceof, athrow 10
  • 12. JVM specific bytecodes • fast_igetfield, fast_iputfield – -XX:+RewriteBytecodes • fast_iload2, fast_aaccess_0 – -XX:+RewriteFrequentPairs • fast_binaryswitch • return_register_finalizer 11
  • 13. Bytecode interpreter • C++ and Assembler (template) interpreter • Generated at VM start-up • Run-time code profiling – -XX:CompileThreshold=10000 • Run-time CP resolution and bytecode rewriting • Optimizations – Dispatch table, top-of-stack caching 12
  • 14. Stack • Java (expression) vs. Native (execution) – -XX:ThreadStackSize=320 • Guard pages Empty – -XX:StackShadowPages=20 – -XX:StackYellowPages=2 Shadow – -XX:StackRedPages=1 Frame Frame Frame 13
  • 15. Stack frame SP Expression stack Monitors Method old SP FP old FP Return addr Locals Expression stack Previous frame 14
  • 16. Frame types • Interpreted, Compiled, Native – Different layout • Inlining – 1 frame for multiple nested methods • Deoptimization – When optimistic assumptions fail – (exceptions, class hierarchy changes etc.) 15
  • 17. Threads • Java threads & VM threads • States: in_java, in_vm, in_native, blocked • Thread pointer in register – Fast Thread.currentThread() • Priority policy (0 – normal, 1 – aggressive) – -XX:ThreadPriorityPolicy=N • TLAB allocation – -XX:+UseTLAB, -XX:TLABSize=0 16
  • 18. Synchronization • Simple uncontended lock – CAS • Biased locking – -XX:+UseBiasedLocking – -XX:BiasedLockingStartupDelay=4000 – -XX:BiasedLockingBulkRebiasThreshold=20 – -XX:BiasedLockingBulkRevokeThreshold=40 • Contended lock optimizations – Spin  Yield  Park 17
  • 19. Java-level locks • java.util.concurrent.locks.LockSupport • park() / unpark() • OS-level primitives – Mutex + Condition variable 18
  • 20. wait / notify • What’s wrong with this code? void waitForCompletion() { void setCompleted() { synchronized (lock) { synchronized (lock) { if (!completed) { completed = true; lock.wait(); lock.notifyAll(); } } } } } 19
  • 21. wait / notify • What’s wrong with this code? void waitForCompletion() { void setCompleted() { synchronized (lock) { synchronized (lock) { if (!completed) { completed = true; lock.wait(); lock.notifyAll(); } } } } } • -XX:+FilterSpuriousWakeups 20
  • 22. Object header Unlocked unused hashCode 0 age 0 01 Monitor Thin lock Displaced header ptr 00 Inflated lock Inflated lock ptr 10 Stack Biased lock JavaThread epoch 0 age 1 01 21
  • 23. Safepoints • When? – GC phases – Thread dump – Deoptimization – Revoke/rebias BiasedLock • How? – Interpreted: switch dispatch table – Compiled: page polling – Native: on return and on JNI calls • -XX:+PrintSafepointStatistics 22
  • 24. Native methods • System.loadLibrary() • Lazy linking • Expensive invocation 1. Create stack frame 2. Set up arguments according to native calling convention 3. Pass JNIEnv* and jclass 4. Lock / unlock if synchronized 5. Trace method entry / method exit 6. Check for safepoint 7. Check exceptions 23
  • 25. JNI functions • Executed in VM context • Check for safepoint • jobject == index in thread-local JNIHandles array • Optional verification – -XX:+CheckJNICalls 24
  • 26. Exceptions • Which code is faster? for (;;) { try { int index = getNextIndex(); for (;;) { if (index >= arr.length) { int index = getNextIndex(); break; sum += arr[index]; } } sum += array[index]; } catch (IndexOutOfBoundsException e) { } // break } 25
  • 27. Exceptions • Which code is faster? for (;;) { try { int index = getNextIndex(); for (;;) { if (index >= arr.length) { int index = getNextIndex(); break; sum += arr[index]; } } sum += array[index]; } catch (IndexOutOfBoundsException e) { } // break } • try-catch is free (exception tables) • throw is expensive (find handler, unwind stack, release locks, build stack trace) 26
  • 28. Reflection • getDeclaredFields(), getDeclaredMethods() – VM Internal structures  Java representation • Field getters and setters – sun.misc.Unsafe • Method.invoke() 1. Native implementation 2. Dynamic bytecode generation (up to 10x faster) -Dsun.reflect.inflationThreshold=15 27
  • 29. MethodAccessor example • void Point.move(float x, float y, boolean relative); class PointMove_MethodAccessor implements MethodAccessor { public Object invoke(Object target, Object[] args) { float x = ((Float) args[0]).floatValue(); float y = ((Float) args[1]).floatValue(); boolean relative = ((Boolean) args[2]).booleanValue(); try { ((Point) target).move(x, y, relative); } catch (Throwable t) { throw new InvocationTargetException(t); } return null; } } 28
  • 30. Troubleshooting • Signal handler (SIGSEGV, SIGILL, SIGFPE…) • Not all SEGV are fatal – Polling page – Implicit NullPointerException, StackOverflowError • hs_err.log – Threads, Stack frames, Memory map – Registers, Top of stack, Instructions – -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly 29
  • 31. Still much to learn 30
  • 32. Thank you! • OpenJDK sources – http://hg.openjdk.java.net • Contacts – andrey.pangin@odnoklassniki.ru • Open Source @ Odnoklassniki – https://github.com/odnoklassniki • Career @ Odnoklassniki – http://v.ok.ru 31