Java virtual machine


A Java virtual machine is a virtual machine that enables a computer to run Java programs as well as programs written in other languages, other languages referred to as JVM languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes what is required in a JVM implementation. Having a specification ensures interoperability of Java programs across different implementations so that program authors using the Java Development Kit need not worry about idiosyncrasies of the underlying hardware platform.
The JVM reference implementation is developed by the OpenJDK project as open source code and includes a JIT compiler called HotSpot. The commercially supported Java releases available from Oracle are based on the OpenJDK runtime. Eclipse OpenJ9 is another open source JVM for OpenJDK.

JVM specification

The Java virtual machine is an abstract computer defined by a specification. It is a part of the Java Runtime Environment. The garbage collection algorithm used and any internal optimization of the Java virtual machine instructions are not specified. The main reason for this omission is to not unnecessarily constrain implementers. Any Java application can be run only inside some concrete implementation of the abstract specification of the Java virtual machine.
Starting with Java Platform, Standard Edition 5.0, changes to the JVM specification have been developed under the Java Community Process as JSR 924., changes to the specification to support changes proposed to the class file format are being done as a maintenance release of JSR 924. The specification for the JVM was published as the blue book, whose preface states:
The most commonly used Java virtual machine is Oracle's HotSpot.
Oracle owns the Java trademark and may allow its use to certify implementation suites as fully compatible with Oracle's specification.

Garbage collectors

Garbage collectors available in Java OpenJDKs virtual machine include:
  • Serial
  • Parallel
  • CMS
  • G1
  • ZGC
  • Epsilon
  • Shenandoah
  • GenZGC
  • GenShen
  • IBM Metronome
  • SAP
  • Azul C4
Java's design philosophy revolves around the assumption of a garbage collector. Unlike languages such as C++ and Rust, deterministic memory management through a delete keyword is not possible. Even introducing such a feature is not possible, due to a lack of ownership, aside from using Security of the Java software platform#The sun.misc.Unsafe class| or through Java Native Interface#Foreign Function and Memory API| to allocate/deallocate memory outside the Java [|heap]. Due to Java primarily using heap-based allocation, objects are stored as references, and deletion would result in dangling pointers.

Foo a = new Foo;
Foo b = a;
delete a;
System.out.println;

Virtual machine architecture

The JVM operates on specific types of data as specified in Java Virtual Machine specifications. The data types can be divided into primitive types and reference types. long and double types, which are 64-bits, are supported natively, but consume two units of storage in a frame's local variables or operand stack, since each unit is 32 bits. boolean, byte, short, and char types are all sign-extended and operated on as 32-bit integers, the same as int types. The smaller types only have a few type-specific instructions for loading, storing, and type conversion. boolean is operated on as 8-bit byte values, with 0 representing false and 1 representing true.
The JVM has a garbage-collected heap for storing objects and arrays. Code, constants, and other class data are stored in the "method area". The method area is logically part of the heap, but implementations may treat the method area separately from the heap, and for example might not garbage collect it. Each JVM thread also has its own call stack, which stores frames. A new frame is created each time a method is called, and the frame is destroyed when that method exits.
Each frame provides an "operand stack" and an array of "local variables". The operand stack is used for operands to run computations and for receiving the return value of a called method, while local variables serve the same purpose as registers and are also used to pass method arguments. Thus, the JVM is both a stack machine and a register machine. In practice, HotSpot eliminates every stack besides the native thread/call stack even when running in Interpreted mode, as its Templating Interpreter technically functions as a compiler.
The JVM uses references and stack/array indexes to address data; it does not use byte addressing like most physical machines do, so it does not neatly fit the usual categorization of 32-bit or 64-bit machines. In one sense, it could be classified as a 32-bit machine, since this is the size of the largest value it natively stores: a 32-bit integer or floating-point value or a 32-bit reference. Because a reference is 32 bits, each program is limited to at most 2 unique references and therefore at most 2 objects. However, each object can be more than one byte large, and potentially very large; the largest possible object is an array of long of length 2 - 1 which would consume 16 GiB of memory, and there could potentially be 2 of these if there were enough memory available. This results in upper bounds that are more comparable to a typical 64-bit byte-addressable machine. A JVM implementation can be designed to run on a processor that natively uses any bit width as long as it correctly implements the integer and floating-point math that the JVM requires. Depending on the method used to implement references, this can limit the number of objects to less than the theoretical maximum. An implementation of the JVM on a 64-bit platform has access to a much larger address space than one on a 32-bit platform, which allows for a much larger heap size and an increased maximum number of threads, which is needed for certain kinds of large applications; however, there can be a performance hit from using a 64-bit implementation compared to a 32-bit implementation.

JVM languages

A JVM language is any language with functionality that can be expressed in terms of a valid class file which can be hosted by the Java Virtual Machine. A class file contains Java Virtual Machine instructions and a symbol table, as well as other ancillary information. The class file format is the hardware- and operating system-independent binary format used to represent compiled classes and interfaces.
There are several JVM languages, both old languages ported to JVM and completely new languages. JRuby and Jython are perhaps the most well-known ports of existing languages, i.e. Ruby and Python respectively. Of the new languages that have been created from scratch to compile to Java bytecode, Clojure, Groovy, Scala and Kotlin may be the most popular ones. A notable feature with the JVM languages is that they are compatible with each other, so that, for example, Scala libraries can be used with Java programs and vice versa.
Java 7 JVM implements JSR 292: Supporting Dynamically Typed Languages on the Java Platform, a new feature which supports dynamically typed languages in the JVM. This feature is developed within the Da Vinci Machine project whose mission is to extend the JVM so that it supports languages other than Java.

Class loader

One of the organizational units of JVM byte code is a class. A class loader implementation must be able to recognize and load anything that conforms to the Java class file format. Any implementation is free to recognize other binary forms besides class files, but it must recognize class files.
The class loader performs three basic activities in this strict order:
  1. Loading: finds and imports the binary data for a type
  2. Linking: performs verification, preparation, and resolution
  3. *Verification: ensures the correctness of the imported type
  4. *Preparation: allocates memory for class variables and initializing the memory to default values
  5. *Resolution: transforms symbolic references from the type into direct references.
  6. Initialization: invokes Java code that initializes class variables to their proper starting values.
In general, there are three types of class loader: bootstrap class loader, extension class loader and System / Application class loader.
Every Java virtual machine implementation must have a bootstrap class loader that is capable of loading trusted classes, as well as an extension class loader or application class loader. The Java virtual machine specification does not specify how a class loader should locate classes.

Bytecode instructions

The JVM has instructions for the following groups of tasks:
The aim is binary compatibility. Each particular host operating system needs its own implementation of the JVM and runtime. These JVMs interpret the bytecode semantically the same way, but the actual implementation may be different. More complex than just emulating bytecode is compatibly and efficiently implementing the Java core API that must be mapped to each host operating system.
These instructions operate on a set of common rather the native data types of any specific instruction set architecture.

Bytecode verifier

A basic philosophy of Java is that it is inherently safe from the standpoint that no user program can crash the host machine or otherwise interfere inappropriately with other operations on the host machine, and that it is possible to protect certain methods and data structures belonging to trusted code from access or corruption by untrusted code executing within the same JVM. Furthermore, common programmer errors that often led to data corruption or unpredictable behavior such as accessing off the end of an array or using an uninitialized pointer are not allowed to occur. Several features of Java combine to provide this safety, including the class model, the garbage-collected heap, and the verifier.
The JVM verifies all bytecode before it is executed. This verification consists primarily of three types of checks:
  • Branches are always to valid locations
  • Data is always initialized and references are always type-safe
  • Access to private or package private data and methods is rigidly controlled
The first two of these checks take place primarily during the verification step that occurs when a class is loaded and made eligible for use. The third is primarily performed dynamically, when data items or methods of a class are first accessed by another class.
The verifier permits only some bytecode sequences in valid programs, e.g. a jump instruction can only target an instruction within the same method. Furthermore, the verifier ensures that any given instruction operates on a fixed stack location, allowing the JIT compiler to transform stack accesses into fixed register accesses. Because of this, that the JVM is a stack architecture does not imply a speed penalty for emulation on register-based architectures when using a JIT compiler. In the face of the code-verified JVM architecture, it makes no difference to a JIT compiler whether it gets named imaginary registers or imaginary stack positions that must be allocated to the target architecture's registers. In fact, code verification makes the JVM different from a classic stack architecture, of which efficient emulation with a JIT compiler is more complicated and typically carried out by a slower interpreter. Additionally, the Interpreter used by the default JVM is a special type known as a Template Interpreter, which translates bytecode directly to native, register based machine language rather than emulate a stack like a typical interpreter. In many aspects the HotSpot Interpreter can be considered a JIT compiler rather than a true interpreter, meaning the stack architecture that the bytecode targets is not actually used in the implementation, but merely a specification for the intermediate representation that can well be implemented in a register based architecture. Another instance of a stack architecture being merely a specification and implemented in a register based virtual machine is the Common Language Runtime.
The original specification for the bytecode verifier used natural language that was incomplete or incorrect in some respects. A number of attempts have been made to specify the JVM as a formal system. By doing this, the security of current JVM implementations can more thoroughly be analyzed, and potential security exploits prevented. It will also be possible to optimize the JVM by skipping unnecessary safety checks, if the application being run is proven to be safe.