Sub topic 3
The constant pool and symbolic references
This chapter assumes you can compile and run Java programs with javac and java. It also assumes you know what a class file is, as covered in the previous chapter. You should be comfortable reading the output of javap -c.
What the constant pool is
A class file does not store names, strings, or large numbers inline in its instructions. It stores them once, in a table called the constant pool, and the instructions refer to table entries by index. A getstatic #2 instruction means "use entry 2 of the pool". The entry says which field that is.
Four rules cover most of what you need to know about the table:
- Indexes start at 1. The class file stores
constant_pool_count, which is the number of entries plus one. Index 0 is never valid. - Each entry starts with a one-byte tag that says what kind of entry it is and how many bytes follow.
longanddoubleentries take two index slots. The slot after them is unusable.- Entries refer to other entries by index, so a single method reference is built from several entries.
Kinds of entries
| Tag | Entry | Holds |
|---|---|---|
| 1 | `CONSTANT_Utf8` | Text in modified UTF-8: names, descriptors, string contents |
| 3, 4 | `Integer`, `Float` | A 4-byte value |
| 5, 6 | `Long`, `Double` | An 8-byte value, two slots |
| 7 | `Class` | Index of a Utf8 entry with the class's internal name, such as `java/lang/Math` |
| 8 | `String` | Index of a Utf8 entry with the characters of a string literal |
| 9, 10, 11 | `Fieldref`, `Methodref`, `InterfaceMethodref` | A `Class` index and a `NameAndType` index |
| 12 | `NameAndType` | Utf8 indexes for a name and a descriptor |
| 15, 16, 18 (and 17) | `MethodHandle`, `MethodType`, `InvokeDynamic` (and `Dynamic`) | Support for lambdas, string concatenation, and similar |
| 19, 20 | `Module`, `Package` | Used in `module-info.class` |
Only Utf8, the numeric entries, and String hold literal data. Every other entry is a pointer to other entries.
Symbolic references
A Methodref entry does not contain a memory address or a vtable slot. It contains three pieces of text, reached through other entries: the class name, the method name, and the method descriptor. This is a symbolic reference. The compiler cannot know where Math.max will live in memory, because the class may not be loaded yet and may come from a different JAR at run time. So it records only what to look for.
The diagram shows how one method reference is assembled.
The descriptor is part of the reference. (II)I means "takes two ints, returns an int". The JVM matches on name and descriptor together, so max(II)I and max(JJ)J are different methods.
Reading the pool with javap -v
Here is a small class that uses a string literal, a field, and two methods:
public class Greeter {
public static void main(String[] args) {
System.out.println("hello");
System.out.println(Math.max(3, 70000));
}
}Compile it and run javap -v Greeter. The output below is abridged. Your index numbers and extra entries may differ slightly between compiler versions.
Constant pool:
#1 = Methodref #8.#9 // java/lang/Object."<init>":()V
#2 = Fieldref #10.#11 // java/lang/System.out:Ljava/io/PrintStream;
#3 = String #12 // hello
#4 = Methodref #13.#14 // java/io/PrintStream.println:(Ljava/lang/String;)V
#5 = Integer 70000
#6 = Methodref #15.#16 // java/lang/Math.max:(II)I
#7 = Methodref #13.#17 // java/io/PrintStream.println:(I)V
...
public static void main(java.lang.String[]);
Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String hello
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: getstatic #2
11: iconst_3
12: ldc #5 // int 70000
14: invokestatic #6 // Method java/lang/Math.max:(II)I
17: invokevirtual #7 // Method java/io/PrintStream.println:(I)V
20: returnjavap prints the // comments for you by following the indexes. In the raw file only the numbers are there.
Notice the following:
getstatic #2appears twice, and both uses share oneFieldref. Each distinct member is stored once per class.iconst_3has no pool entry because the value 3 is encoded in the opcode itself. Small ints useiconst_*,bipush(-128 to 127), orsipush(-32768 to 32767). Larger ints, floats, strings, and class literals go throughldc.ldctakes a one-byte index. If the index is above 255, the compiler usesldc_w, which takes two bytes.longanddoubleconstants useldc2_w.
Dumping the pool yourself
The pool layout is simple enough to parse in a few lines. This program prints each entry's raw index form. It uses readUTF, whose format (a two-byte length and then modified UTF-8) is the same as CONSTANT_Utf8.
import java.io.DataInputStream;
import java.io.FileInputStream;
public class PoolDump {
public static void main(String[] args) throws Exception {
try (DataInputStream in = new DataInputStream(new FileInputStream(args[0]))) {
in.readInt(); // magic
in.readUnsignedShort(); // minor
in.readUnsignedShort(); // major
int count = in.readUnsignedShort();
for (int i = 1; i < count; i++) {
int tag = in.readUnsignedByte();
switch (tag) {
case 1:
System.out.printf("#%d Utf8 %s%n", i, in.readUTF());
break;
case 3:
System.out.printf("#%d Integer %d%n", i, in.readInt());
break;
case 4:
System.out.printf("#%d Float %s%n", i, in.readFloat());
break;
case 5:
System.out.printf("#%d Long %d%n", i, in.readLong());
i++; // a Long occupies two slots
break;
case 6:
System.out.printf("#%d Double %s%n", i, in.readDouble());
i++; // a Double occupies two slots
break;
case 7: case 8: case 16: case 19: case 20:
System.out.printf("#%d tag=%d -> #%d%n", i, tag, in.readUnsignedShort());
break;
case 9: case 10: case 11: case 12: case 17: case 18:
System.out.printf("#%d tag=%d -> #%d, #%d%n", i, tag,
in.readUnsignedShort(), in.readUnsignedShort());
break;
case 15:
System.out.printf("#%d MethodHandle kind=%d -> #%d%n", i,
in.readUnsignedByte(), in.readUnsignedShort());
break;
default:
throw new IllegalStateException("Unknown tag " + tag + " at #" + i);
}
}
}
}
}Run javac Greeter.java PoolDump.java and then java PoolDump Greeter.class. You will see the Utf8 entries for java/lang/Math, max, and (II)I, and the Methodref entry that ties them together.
From class file pool to runtime constant pool
When the JVM loads a class, it builds a runtime constant pool for it from the file's table. The runtime pool lives in metaspace, as the earlier chapter on data areas described. At first its reference entries are still symbolic. Resolution is the step that turns a symbolic entry into a direct reference, such as a loaded Class object, a method, or a field slot.
HotSpot resolves lazily. Nothing is resolved while loading. The first time invokestatic #6 executes, the JVM does the following:
- It resolves the
Classentry. This asks the defining class's loader forjava/lang/Math, which may trigger loading. - It looks up
maxwith descriptor(II)Iin that class and its supertypes. - It checks that the calling class has access to the member.
- It records the result in the runtime pool entry. Later executions of that instruction skip the lookup.
Two consequences follow. A class you never run through a given instruction never pays for resolving it. A broken reference, such as a missing class, stays hidden until the code path runs.
A String entry works similarly. The Utf8 text is turned into a java.lang.String object when ldc first executes, and the object is interned. This is why two identical literals in different classes are == to each other.
What goes wrong at resolution
Resolution failures show up as LinkageError subclasses at run time:
| Error | Typical cause |
|---|---|
| `NoClassDefFoundError` | The `Class` entry could not be loaded |
| `NoSuchMethodError` / `NoSuchFieldError` | The class exists, but no member matches the name and descriptor |
| `IllegalAccessError` | The member exists but is not accessible from the caller |
| `IncompatibleClassChangeError` | A class was changed in a way that breaks the reference, such as a field becoming a method |
The most common real case is a binary compatibility break. Suppose Lib.add changes from int add(int, int) to long add(int, int), and you replace only Lib.class without recompiling the callers. The caller's pool still says add:(II)I. The source still looks fine, but the JVM throws NoSuchMethodError the first time that line runs. Recompiling the caller fixes it, because the compiler writes a new descriptor.
A failed resolution is cached too. Later attempts to resolve the same entry fail with the same error and do not retry the lookup.
Constants inlined at compile time
A static final field initialized with a compile-time constant is copied into each user's constant pool, not referenced. If Config.TIMEOUT is static final int TIMEOUT = 30, a caller compiles to bipush 30. It holds no Fieldref to Config. This is why reading such a constant does not initialize the class, as the Lazy example showed earlier. It is also why changing the constant and recompiling only Config leaves the old value in every other class.
Limits and encoding
- The pool count is a two-byte value, so a class has at most 65,534 usable entries. Very large generated classes can hit this limit and fail to compile.
- A
Utf8entry holds at most 65,535 bytes. A string literal longer than that fails at compile time, with an error such as "constant string too long". - Modified UTF-8 differs from standard UTF-8 in two ways. The null character is encoded as two bytes (
C0 80), and characters outside the Basic Multilingual Plane are stored as two three-byte surrogate halves. A tool that decodes pool text with a standard UTF-8 decoder can get these wrong.
Exercise
A library class Util has static int size(). Your application class App calls it. Someone replaces Util.class with a new version where the method is static long size(), and does not recompile App. What happens when App runs the call, and which part of the Methodref explains it?
Show answer
The call throws NoSuchMethodError when that instruction first executes, not when App is loaded. The Methodref in App's pool points to a NameAndType entry with the descriptor ()I. Resolution looks for a method named size with exactly that descriptor. The new Util only has size()J, so the lookup fails. Recompiling App writes ()J and fixes the problem.
Exercise
In PoolDump, why does the Long case increment i an extra time?
Show answer
A Long or Double entry takes two slots in the pool, and the second slot is unusable and not stored in the file. Without the extra i++, the loop would try to read a tag from the next entry's data at the wrong index numbering, and every later index it printed would be off by one.