JVM

JVM Languages

  • Java
  • Scala
  • Groovy
  • Closure
  • Javascript(Nashorn)
  • Python(Jython)
  • Ruby(JRuby)

JVM Memory

  • Eden
  • Survivor 1 + Survivor 2
  • Old (or Tenured)
  • Metaspace(Since Java 8) / Perm Generation (until Java 7)

Purpose of Each Region

  • Eden Generation: newly constructed objects. Short-lived objects will soon be collected as garbage
  • Survivor: Objects that survived Minor GC are not directly promoted to the Old Generation. They are kept in the Survivor region for a certain number of Minor GC collections. Only if they survive certain number of Minor GC collections can they be promoted to the Old Generation.
  • Old Generation: long-lived objects are promoted to old generation. e.g. Application Context, HTTP Sessions, Caches, Connection Pools, etc.
  • Perm Generation: where JVM objects such as Classes, Methods, String Interns, etc. are created.
  • Metaspace: Starting with Java 8, the perm generation has been replaced with Metaspace for performance reasons.

Garbage Collection Types

  • Minor GC: or Scavenge GC. Collect garbage from the Young Generation.
  • Major GC: collect garbage from the Old Generation
  • Full GC: collects garbage from all regions

stop-the-world event

When GC runs, all application threads are paused. In Minor GCs, stop-the-world events occurs, but only momentarily.

Garbage Collection Algorithms


  • G1 Garbage Collector

  • Concurrent Mark Sweep (CMS) Collector

    • Also known as the low latency collection. This is 1 of 2 non-compacting collector.
    • -XX:+UseConcMarkSweepGC
  • Parallel Compacting Collector

    • Young and old generation are both collected in parallel and compacted.
    • -XX:+UseParallelOldGC
  • Parallel Collector

    • Collects new in parallel, but old by serial algorithm.
    • -XX:+UseParallelGC
  • Serial Collector

    • Single CPU collector for both young and old generations. Good for embedded systems without a lot of processing power. By default ergonomics does not use this unless you have less than 2 processors and less than 2GB of memory.
    • -XX:+UseSerialGC

Concurrent vs. Parallel

  • Concurrent: runs along with application threads
  • Parallel: stop the world, multi-threaded

Interpreter vs. JIT Compiler

javac compiles Java code to bytecode; to execute the bytecode, there are 2 options:

  • Interpreter:

    • Read the next byte code to be executed
    • Look at what the byte code is and find the native machine instruction(s) that correspond to it
    • Execute the native machine instruction(s)
    • Go to step 1
  • Just-In-Time compiler:

    • Read all the byte codes for the method that needs to be executed
    • Convert all those byte codes to native machine instructions
    • Execute the generated native machine instructions

Debugging

  • -verbose:gc(打印 GC 日志)
  • -Xloggc:(更全面的 GC 日志)
  • -XX:+PringGCDetail(更详细的输出)
  • -XX:+PrintTenuringDistribution(显示由 JVM 设定的保有阈值)