Sub topic 7
How methods are invoked: invokestatic, invokevirtual and friends
This chapter assumes you can read basic javap -c output, know what the operand stack and local variables of a frame are, and know that the constant pool holds symbolic references. Here you will see how the JVM turns a method call in source code into one of five invocation instructions, and what each does at run time.
One call, two decisions
Every call in Java involves two decisions that happen at different times.
- Compile time.
javacpicks the method signature. It resolves overloads using the static types of the arguments, then writes a method descriptor such as(I)Ior()Ljava/lang/String;into the constant pool. - Run time. The JVM picks which method body runs. For instance methods this depends on the actual class of the receiver object, not on the declared type of the variable.
Keep these two apart. Most confusion about overloading versus overriding comes from mixing them up.
The five invocation instructions
Each invocation instruction takes a constant pool index. That index points to a Methodref or InterfaceMethodref entry holding the class name, method name and descriptor. The JVM pops the arguments (and the receiver, for instance calls) from the operand stack. It pushes the return value, if there is one, onto the caller's operand stack.
| Instruction | Used for | Target chosen |
|---|---|---|
| `invokestatic` | Static methods | The resolved method itself. There is no receiver. |
| `invokevirtual` | Instance methods on a class type | Selected at run time from the receiver's class |
| `invokeinterface` | Instance methods on an interface type | Selected at run time from the receiver's class |
| `invokespecial` | Constructors, `super.m()` calls, and (before Java 11) private methods | The resolved method, with no overriding lookup |
| `invokedynamic` | Lambdas, string concatenation, and other call sites linked by a bootstrap method | Decided by the call site's bootstrap method on first execution |
Seeing them in a real class
The following class uses all of them except a plain private call.
public class Invoke {
interface Shape { double area(); }
static class Square implements Shape {
final double side;
Square(double side) { this.side = side; }
public double area() { return side * side; }
}
static class Base {
String name() { return "base"; }
}
static class Derived extends Base {
@Override
String name() { return "derived+" + super.name(); }
}
static int twice(int x) { return x * 2; }
public static void main(String[] args) {
Shape s = new Square(3);
Base b = new Derived();
System.out.println(twice(4));
System.out.println(s.area());
System.out.println(b.name());
Runnable r = () -> System.out.println("hi");
r.run();
}
}Compile it and run javap -c -p 'Invoke$Derived' and javap -c -p Invoke. The excerpts below are trimmed. The # indexes and offsets on your machine will differ.
// Invoke$Derived.name()
aload_0
invokespecial #3 // Method Invoke$Base.name:()Ljava/lang/String;
invokedynamic #4 // makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
areturn
// Invoke.main(String[])
new #2 // class Invoke$Square
dup
ldc2_w #3 // double 3.0d
invokespecial #5 // Method Invoke$Square."<init>":(D)V
astore_1
...
invokestatic #9 // Method twice:(I)I
...
invokeinterface #12, 1 // InterfaceMethod Invoke$Shape.area:()D
...
invokevirtual #15 // Method Invoke$Base.name:()Ljava/lang/String;
...
invokedynamic #17 // InvokeDynamic #0:run:()Ljava/lang/Runnable;
astore_3
aload_3
invokeinterface #18, 1 // InterfaceMethod java/lang/Runnable.run:()VSeveral things in this output are worth noting.
newonly allocates an uninitialized object. The constructor call is a separateinvokespecialon the<init>method. Thedupkeeps a second reference on the stack so that, after the constructor consumes one, the other can be stored withastore_1.super.name()usesinvokespecial. The JVM must callBase.name, not look up the receiver's class again. A virtual lookup would findDerived.nameand recurse forever.- The call
b.name()namesInvoke$Basein the instruction, becausebis declared asBase. The method that runs isDerived.name. That is the run-time decision. - The lambda is an
invokedynamicthat produces theRunnable. Callingr.run()afterwards is an ordinaryinvokeinterface. - With a Java 9 or later target,
"derived+" + ...compiles toinvokedynamicbacked byStringConcatFactory. Java 8 class files useStringBuildercalls instead.
Choosing the instruction
Resolution and selection
Running an invocation instruction involves two separate JVM steps.
Resolution turns the symbolic reference into a concrete method. The JVM resolves the class named in the reference. It then searches that class, its superclasses and its superinterfaces for a method with the given name and descriptor. Resolution also checks access rules. HotSpot does this lazily, the first time the instruction executes, and it caches the result for that call site.
Selection applies only to invokevirtual and invokeinterface. Starting from the receiver's actual class, the JVM finds the method that overrides the resolved one. HotSpot implements this with a per-class table of method entries (a vtable for class methods, an itable for interface methods). That implementation detail can change between JVMs. The specification only requires the observable result.
invokestatic and invokespecial skip selection. Their target is the resolved method.
Overloads are fixed at compile time
Selection looks only at the receiver. It never looks at the run-time types of the arguments. This program shows what that means.
public class Overload {
static class Animal {}
static class Dog extends Animal {}
static String describe(Animal a) { return "animal"; }
static String describe(Dog d) { return "dog"; }
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(describe(a));
System.out.println(describe(new Dog()));
}
}It prints animal and then dog. The first call site was compiled with the descriptor (LOverload$Animal;)Ljava/lang/String; because a has the static type Animal. The object's real class is irrelevant to that choice. Run javap -c Overload and compare the two invokestatic descriptors.
Final, private and interface edge cases
finalmethods still useinvokevirtual. Thefinalmodifier is checked by the verifier and the class loader, not encoded in the instruction. The JIT compiler can still skip the table lookup when it knows only one implementation exists.- Private methods were called with
invokespecialbefore Java 11. Java 11 introduced nestmates, so a class and its nested classes can call each other's private members directly. Code compiled for Java 11 can therefore useinvokevirtual(orinvokeinterfacefor private interface methods) for private calls. If you seeinvokespecialin older class files, this is the reason. - Default methods are found during resolution and selection like any other interface method. A call such as
Iface.super.m()compiles toinvokespecialwith anInterfaceMethodref. invokeinterfacehas an extra operand, the argument count. It is a historical leftover. Its trailing zero byte is required.
Errors caused by invocation
Because class files are linked separately from compilation, a call can fail even though it compiled. Typical failures are:
NoSuchMethodError: resolution found no method with that name and descriptor. This usually means a dependency was recompiled with a changed signature and the caller was not.AbstractMethodError: selection found only an abstract method. This often appears when an interface gains a method that an old implementing class lacks.IncompatibleClassChangeErrorand its subclasses (such asIllegalAccessErrorandIncompatibleClassChangeErrorfor static versus instance mismatch): the target changed kind, for example an instance method became static.NullPointerException: the receiver for an instance call wasnull. All instance invocations throw it before the call.
Exercise
In Derived.name(), super.name() compiles to invokespecial. Suppose it compiled to invokevirtual Invoke$Base.name instead. What would happen when you call new Derived().name(), and why?
Show answer
The JVM would resolve Base.name, then select a method from the receiver's actual class, Derived. Selection finds Derived.name, which calls itself again. The result is unbounded recursion and a StackOverflowError. invokespecial avoids selection and calls Base.name directly.
Exercise
A class Client was compiled against Lib version 1, which had int parse(String s). Lib version 2 changes it to long parse(String s). You replace the Lib jar but do not recompile Client. Which error do you get, and when?
Show answer
A NoSuchMethodError, thrown when Client's invokevirtual or invokestatic for parse is first executed. The constant pool entry holds the descriptor (Ljava/lang/String;)I. Lib now only has (Ljava/lang/String;)J. Resolution matches name and descriptor exactly, so the lookup fails.