Hey, guys, it’s time to roll again.

Cold Wind has prepared these questions about the JVM that you hope will be helpful.

0 What is the relationship between JDK, JRE, and JVM?

From large to small, JDK > JRE > JVM.

Java Development Kit(including Javac, JavAP, etc.) + JRE

JRE = JVM + Java CoreLib

Is Java compiled or interpreted?

First, Java files are compiled into class files and loaded into memory by the classLoader.

Once loaded into memory, there will be different processing routines.

  • The bytecode interpreter interprets it sentence by sentence and passes it off to the execution engine, most of the time.
  • For frequently used code, such as loops, the JIT just-in-time compiler compiles native code and hands it directly to the execution engine to improve execution efficiency.

By default, the JVM uses mixed mode. Of course, other modes can also be adjusted according to the actual situation.

model advantages disadvantages
Mixed mode The interpretation execution begins, and then the hot code is detected and compiled
Explain pattern Start the fast Perform slow
Compilation mode Slow start Perform quick

So, JAVA can’t be interpreted or compiled; it’s all about setup.

Does the JVM only execute Java files?

In fact, any program that can be compiled into a class file according to the class file specification can be executed on the JVM, such as Scala, Kotlin, etc.

Do you know how many implementations the JVM has?

The most common implementation is HotSpot, which is the virtual machine used in sun’s JDK today.

C:\Users> java -version

java version "1.8.0 comes with _191"

Java(TM) SE Runtime Environment (build 1.8.0_191-b12)

Java HotSpot(TM) Client VM (build 25.191-b12, mixed mode)

Copy the code

In addition, there are JRockit, IBM’S J9, MicroSoft VM, Taobao VM and so on.

What does a class file contain?

A class file is a Java compiled binary file that conforms to a certain specification. It roughly contains magic numbers (class file identifiers), JDK versions, constant pools, access tags, interfaces, methods, properties, and other information.

5 Talk about the object creation process.

The first is the class loading process, which is roughly divided into three steps:

  • Loading file binary byte streams into memory
  • Linking
    • Verification: verifies that the class file complies with format specifications, such as starting with CAFEBABE.
    • Preparation, in which JAVA static variables are assigned default values, such as int, which defaults to 0.
    • Resolution converts symbolic references in the constant pool to direct memory addresses.
  • Initializing, static variable initialization, class initialization code execution, static statement block execution.

Second, there is the object creation process.

  • Build objects and allocate memory for them

  • Assign default values to member variables

  • Initialize an object

    • Member variables assign initial values
    • Execute constructor

What is the class loader for the JVM? (What does parental delegation mean?)

There are three levels of classloaders, from top to bottom:

  • BootStrapClassLoader loads classes such as rt.jar.
  • ExtClassLoader loads the JAR under jre\lib\ext.
  • AppClassLoader Loads classes in the classpath.

When a class needs to be loaded into memory, the lowest level AppClassLoader (which does not load the class first) checks to see if it has been loaded and returns the result if the APP has. If App is not loaded, continue to look up to see if the parent loader Ext is loaded, return if Ext is loaded, request the parent loader BootStrap if Ext is not loaded, return if BootStrap is loaded.

If it is not loaded, BootStrap checks whether it should be loaded by itself. If it is loaded, BootStrap checks whether it should be loaded by itself. If it is not, the class loader is found level by level until the class is finally loaded.

If all classLoaders are not loaded, an error ClassNotFoundException is reported.

In this way,Search from the bottom up, and load from the top downThis is called the parent delegate mechanism.

The corresponding parent delegate code (recursively) :

protected Class<? > loadClass(String paramString, boolean paramBoolean)

    throws ClassNotFoundException

  {

    synchronized (getClassLoadingLock(paramString))

    {

      Class localClass = findLoadedClass(paramString);

      if (localClass == null)

      {

        long l1 = System.nanoTime();

        try

        {

          if(this.parent ! = null) {

            localClass = this.parent.loadClass(paramString, false);

          } else {

            localClass = findBootstrapClassOrNull(paramString);

          }

        }

        catch (ClassNotFoundException localClassNotFoundException) {}

        if (localClass == null)

        {

          long l2 = System.nanoTime();

          localClass = findClass(paramString);

          PerfCounter.getParentDelegationTime().addTime(l2 - l1);

          PerfCounter.getFindClassTime().addElapsedTimeFrom(l2);

          PerfCounter.getFindClasses().increment();

        }

      }

      if (paramBoolean) {

        resolveClass(localClass);

      }

      return localClass;

    }

  }

Copy the code

The main purpose of the parent delegation mechanism is for security, preventing custom classes from arbitrarily overwriting the system’s native classes.

7 When is the classLoader.loadClass method used?

When Spring generates a dynamic proxy class, you need to manually load the proxy class into memory. Or hot deployment of Tomcat, where the modified class is manually loaded into memory.

8 How to customize a class loader?

The findClass method of the ClassLoader class throws an exception.

A custom class loader only needs to:

  • Inherit this
  • Override template method findClass
    • Call super.defineclass to convert the binary byte stream into a Class object.

In addition, overwriting the loadClass method can break Java’s parent delegate mechanism.

JAVA is lazyLoading (more specifically, lazyInitializing). When will classes be initialized by the system?

  • new
  • Class.forName
  • Access a static variable or method of a class

Does not initialize

  • Access static final variables

Do we need volatile to define singletons in singletons?

Yes, voldatile prevents JVM instructions from reordering and ensures that the object is returned after it is fully initialized.

Instruction reordering can result in semi-initialized objects.

How does volatile prevent instruction reordering and make memory visible?

Voldatile prevents instruction reordering by inserting Memory barriers. Volatile is implemented at three levels:

  • Bytecode layer

When a variable I is volatile, access_flag ACC_VOLATILE is added to the compiled bytecode.

  • The JVM level

When the JVM interprets the bytecode access flag ACC_VOLATILE, it adds a barrier before the variable is read or written: StoreStoreBarrier is added before all volatile writes and StoreLoadBarrier is added after all volatile writes.

Add LoadLoadBarrier to all volatile reads and LoadStoreBarrier to all volatile reads.


  • Operating system layer (x86 as an example)

Through assembly instruction LOCK to achieve. Write operations after lock write back the modified data to main memory, while invalidating other CPU cache data, thus reloading data from main memory. The lock instruction prevents reordering of instructions on both sides of the barrier.

What about the implementation details of synchronized?

Like volatile, it has three levels:

  • Bytecode layer

Monitorenter and Monitorexit are used before and after synchronized blocks. Or add ACC_SYNCHRONIZED access identifier;

  • The JVM level

The synchronization function provided by the operating system is called

  • Operating system layer (x86 as an example)

It is actually a LOCK CMPXCHG instruction that prevents other threads from entering.

What is the memory layout of the object?

Common object components:

  • Object header Markword 8 bytes

  • ClassPoiter pointer

    • Open compression (XX: + UseCompressedClassPointers) 4 bytes
    • Do not enable 8 bytes compression
  • The object data

    • The reference type (-xx :+UseCompressedOops) enables compression to 4 bytes
    • Reference types do not enable compression of 8 bytes
    • Basic types of
  • Align objects that are not multiples of 8. Align (padding)

An array object is one more array length (4 bytes) than a normal object

For example: How many bytes does the new Object() take up?

ClassPoiter pointer 8 + ClassPoiter pointer 4 + padding 4 = 16 bytes;

Uncompressed: object header 8 + ClassPoiter pointer 8 = 16 bytes


Cache line alignment pseudo-share, where the CPu reads the entire cache line into the cache, which is 64 bytes in most implementations.

Resolving pseudo sharing


JVM runtime data areas and common instructions

JVM runtime data area

  • Program Technology (Program Counter)

  • The stack

    • JVM stack (one stack per thread)
      • Stack frames (one stack frame for each method)

        • Local variable scale
        • The operand stack
        • Dynamic link
        • Return value address
    • Local method stack
  • Direct memory (MEMORY NIO that the JVM can access directly)

  • Methods area

  • The heap

  • Methods area

      1. PermSpace (<1.8) String constants are specified when PermSpace FGC does not clean up size startup and cannot be changed
      1. Meta Space (>=1.8) String constants in the heap trigger FGC cleanup. If not set, maximum is physical memory