JVM中pop与pop2指令的差异及pop2含义、用法咨询
pop vs pop2 Instructions Let’s walk through your questions step by step, using the JVM spec definitions you referenced:
1. Key Differences Between pop and pop2
The core distinction lies in the types of values they handle and how many stack slots they consume:
pop(opcode0x57): Only works with category 1 values. These are types that occupy a single slot on the JVM operand stack, likeint,float,reference,byte,short,char. It removes exactly one value (one stack slot) from the top of the operand stack.pop2(opcode0x58): Handles two scenarios:- Two separate category 1 values (removing two stack slots total)
- One category 2 value (removing two stack slots total, since category 2 types like
longanddoubleoccupy two consecutive slots on the operand stack, even though they’re logically a single value)
2. What Does "Pops 1 or 2 Values" Mean for pop2?
This wording refers to the logical count of values being removed, not the physical stack slots:
- When dealing with a category 2 value (e.g., a
long), the operand stack holds it as two contiguous slots.pop2removes both slots, but logically this is one single value being popped. - When dealing with two category 1 values (e.g., two
ints),pop2removes both individual values (each taking one slot), so that’s two logical values being popped.
In both cases, the physical number of stack slots removed is two— the "1 or 2" describes how we think about the values in the JVM’s type system.
3. Practical Examples of pop2
Let’s look at Java code and its corresponding bytecode to see pop2 in action.
Example 1: Popping a Category 2 Value (long)
public class Pop2Demo { public void popLong() { long myLong = 42L; // myLong is no longer used after this point } }
Compile this and run javap -c Pop2Demo to see the bytecode:
public void popLong(); Code: 0: ldc2_w #2 // long 42l 3: astore_1 4: pop2 5: return
Here, ldc2_w loads the long value onto the operand stack (taking two slots), astore_1 stores it in local variable 1, then pop2 cleans up the unused value from the stack.
Example 2: Popping Two Category 1 Values (ints)
public class Pop2Demo { public void popTwoInts() { int a = 10; int b = 20; // Neither a nor b is used after this point } }
The bytecode for this method will look like:
public void popTwoInts(); Code: 0: bipush 10 2: astore_1 3: bipush 20 5: astore_2 6: pop2 7: return
Instead of generating two separate pop instructions, the JVM uses pop2 to efficiently remove both unused int values from the stack in one step.
内容的提问来源于stack exchange,提问作者user9751996

