Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the Java bytecodes for invoking methods implicitly acquire and release monitors?

I've been reading up on the Java Virtual Machine Instruction Set and noticed that when using instructions to invoke methods (e.g. invokestatic, invokevirtual, etc.) that are marked synchronized, it's up to that particular bytecode instruction to acquire the monitor on the receiver object. Similarly, when returning from a method, it's up to the instruction that leaves the method to release the monitor when the method is synchronized. This seems strange, given that there are explicit monitorenter and monitorexit bytecodes for managing monitors. Is there a particular reason for the JVM designing these instructions this way, rather than just compiling the methods to include the monitorenter and monitorexit instructions where appropriate?

like image 896
templatetypedef Avatar asked Feb 26 '11 22:02

templatetypedef


People also ask

What is opcodes in Java?

A Java Virtual Machine instruction consists of an opcode specifying the operation to be performed, followed by zero or more operands embodying values to be operated upon. This chapter gives details about the format of each Java Virtual Machine instruction and the operation it performs.

What is LDC in Java?

ByteCode:ldc pushes a one-word constant onto the operand stack. ldc takes a single parameter, , which is the value to push. Most of the bytecodes in JVM can figure out their name by the code description.

Does JVM have registers?

The JVM has a program counter and three registers that manage the stack. It has few registers because the bytecode instructions of the JVM operate primarily on the stack. This stack-oriented design helps keep the JVM's instruction set and implementation small.

Is JVM open source?

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.


1 Answers

Back in the mid-90s, there were no Java JIT compilers and micro-synchronisation was thought to be a really great idea.

So you are calling these synchronised method a lot. Even Vector has 'em! You could deal without the extra bytecodes to interpret.

But not just when the code is being run. The class file is bigger. Extra instructions, but also setting up the try/finally tables and verification that something naughty hasn't been slipped in.

Just my guess.

like image 175
Tom Hawtin - tackline Avatar answered Sep 30 '22 17:09

Tom Hawtin - tackline