Java ByteCode Part 2

9 篇文章 0 订阅

原文链接http://blog.jamesdbloom.com/JavaCodeToByteCode_PartTwo.html

Understanding how Java code is compiled into byte code and executed on a Java Virtual Machine (JVM) is critical because it helps you understand what is happening as your program executes. This understanding not only ensures that language features make logical sense but also that it is possible to understand the trade offs and side effects when making certain discussions.

This article explains how Java code is compiled into byte code and executed on the JVM. To understand the internal architecture in the JVM and different memory areas used during byte code execution see my previous article on JVM Internals.

This article is split into three parts, with each part being subdivided into sections. It is possible to read each section in isolation however the concepts will generally build up so it is easiest to read the sections. Each section will cover different Java code structures and explain how these are compiled and executed as byte code, as follows:

This article includes many code example and shows the corresponding typical byte code that is generated. The numbers that precede each instruction (or opcode) in the byte code indicates the byte position. For example an instruction such a 1:iconst_1 is only one byte in length, as there is no operand, so the following byte code would be at 2. An instruction such as 1:bipush 5 would take two bytes, one byte for the opcode bipush and one byte for the operand5. In this case the following byte code would be at 3 as the operand occupied the byte at position 2.

try-catch-finally

When a try-catchtry-finally or try-catch-finally exception handler is compiled an exception table is added into the class file. The exception table stores per-exception handler information such as:

  • Start point
  • End point
  • PC offset for handler code
  • Constant pool index for exception class being caught

This contains information for each exception handler or finally block including the range over which the handler applies, what type of exception is being handled and where the handler code is.

Exceptions can be initiated by:

  • the throw keyword which is compiled to the throw bytecode
  • a Java method, during which an exception with no handler was thrown by the throw bytecode
  • an internal VM-internal call, for example ClassNotFoundExceptionexception thrown during dynamic linking
  • a JNI call to native code

When an exception is thrown the JVM looks for a matching handler in the current method, if none is found the method ends abruptly popping the current stack frame and the exception is re-thrown in the calling method (the new current frame). If no exception handler is found before all frames have been popped then the thread is terminated. This can also cause the JVM itself to terminate if the exception is thrown in the last non-daemon thread, for example if the thread is the main thread.

Finally exception handlers match all types of exceptions and so always execute whenever an exception is thrown. In the case when no exception is thrown a finally block is still executed at the end of a method, this is achieved by adding the finally handler byte codes at the end of the byte code for the try block.

The following code:

public void tryCatchCatchFinally(int i) {
    try {
        i = 2;
    } catch (RuntimeException e) {
        i = 3;
    } finally {
        i = 4;
    }
}

Therefore gets compiled to:

// try block
 0: iconst_2            // load 2 onto operand stack
 1: istore_1            // store top operand to local variable 1
// finally block - no exception
 2: iconst_4            // load 4 onto operand stack
 3: istore_1            // store top operand to local variable 1
 4: goto          20    // jump to return
// catch block
 7: astore_2            // store exception to local variable 2
 8: iconst_3            // load 3 onto operand stack
 9: istore_1            // store top operand to local variable 1
// finally block - after catch block
10: iconst_4            // load 4 onto operand stack
11: istore_1            // store top operand to local variable 1
12: goto          20    // jump to return
// finally block - after exception not caught in catch block
15: astore_3            // store exception to local variable 3
16: iconst_4            // load 4 onto operand stack
17: istore_1            // store top operand to local variable 1
18: aload_3             // load local variable 3 (i.e. exception) onto operand stack
19: athrow              // throw top operand (i.e. propagate up the stack)
20: return              // return

Exception table:
   from   to   target  type
   // jump to catch block for RuntimeException
   0      2    7       Class java/lang/RuntimeException
   // jump to finally block if any exception (other than RuntimeException)
   0      2    15      any
   // jump to finally block if exception in catch block
   7      10   15      any

The example above has three entries in the exception table, as follows:

   from   to   target  type
   0      2    7       Class java/lang/RuntimeException

The from column is inclusive and the to column is exclusive so this entry describes the exception handler for RuntimeExceptions thrown by byte codes 0 and 1. The entry covers the try block and forwards execution to the catchblock if there is a RuntimeException. As this is the first entry in the exception table the JVM exception handling logic will always attempt to match this first before any other handler.

   from   to   target  type
   0      2    15      any

This entry describes the exception handler for all exceptions thrown by byte codes 0 and 1. This handler is used if there is an exception that has not already been caught by the earlier exception handler for RuntimeException. This entry covers the try block and forwards execution to a special version of thefinally block that executes the code in the finally block then re-throws the exception causing the stack frame to be popped allowing exception handlers higher the stack frame to handle this exception.

   from   to   target  type
   7      10    15     any

This entry describes the exception handler for all exceptions thrown by byte codes 7, 8 and 9. This entry covers any exceptions thrown during the catchblock for RuntimeException it forwards execution to a special version of thefinally block that executes the code in the finally block then re-throws the exception causing the stack frame to be popped allowing exception handlers higher the stack frame to handle this exception.

TODO - Add diagram for try-catch-finally

synchronized

Objects in Hotspot JVM are represented by an Ordinary Object Pointer (OOP). An OOP contains two important fields called the mark word and the klass pointer, these are referred to as the two word object header. The mark word contains information such as the identity hash value (is assigned), garbage collection age, and synchronization information such as the object's lock (i.e. monitor). The klass pointer points to an object shared by all instances of the same type that contains information about static fields and a vtable used to support method invocation.

When a thread enters a synchronised block or method, for an object, it attempts to gain ownership of the lock for that object. Since most objects are locked by at most by one thread during it's lifetime, a thread can bias an object's lock towards itself. If the thread gains ownership of the lock the mark field of the OOP is updated and biased toward that thread.

Biased locking makes it much faster for the same thread to reacquire an object's lock. A biased lock is faster because once an object lock is biased towards a thread, that thread can lock and unlock the object without resorting to expensive Compare And Swap (CAS) atomic instructions. CAS is expensive because lock instructions are atomic with respect to all other memory operations and externally visible events on a CPU. This means that lock instructions on pipelined or superscalar CPUs (all modern CPUs) have to wait for all other outstanding instructions to complete their load and store severely affecting instruction parallelism.

If another thread tries to lock the object the bias is reverted. The lock is now either rebaised or simply reverts to normal stack-locking for the remainder of the object's lifetime.

Another way to view biased locking is that the original owner simply delays unlocking the object until it encounters contention.

The mark word can contain the following different states to support synchronisation:

Neutral:
 - Unlocked
No thread has locked this object.
Biased:
 - Locked/Unlocked
 - Unshared
A single thread has locked this object and it is biased towards that thread. This is the most efficient type of locking because it avoids the need for any atomic CAS (Compare And Swap) operations.
Stack-Locked:
 - Locked
 - Shared
 - Uncontended
The mark word points to the stack on the thread that has locked the object. This state is less efficient because locking and unlocking requires the use of an atomic operation (call CAS - Compare And Swap) to update the ownership of the lock. Although this states is less efficient it supports the lock being shared between multiple threads.
Inflated:
 - Locked
 - Shared
 - contented
One thread has locked the object and one or more threads are queued waiting to gain the thread. The mark word points to a heavy-weight objectmonitor structure that contains information about the queued threads.

The JVM handles synchronised methods and synchronised blocks slightly differently. When a new method is executed the JVM checks if it has thesynchronised keyword if it does then an attempt is made to acquire the appropriate object's lock. synchronised blocks instead use two special byte codes, as follows:

monitorenter
The thread that executes this instruction attempts to gain the monitor (i.e. lock) of the reference at the top of the operand stack.
  • If the entry count is zero then the thread enters the monitor and increments the entry count.
  • If the thread already owns the monitor it re-enters the monitor by incrementing the entry count.
  • If another thread owns the monitor the thread blocks until the monitor's entry count is zero.
monitorexit
The thread that executes this instruction decrements the entry count of the reference at the top of the operand stack. If the entry count is zero after it has been decremented that the monitor (i.e. lock) is no longer owned by the thread. Any other threads waiting to own this monitor (due to a  monitorenterinstruction) are now unblocked and can attempt to take ownership.

synchronized blocks are implemented as a try-finally with themonitorenter in the try block and the monitorexit in the finally block. This can be seen in the following code example:

public void synchronizedBlock(int i) {
    synchronized (this) {
        i = 1;
    }
}

This results in the following byte code:

// try block
 0: aload_0            // load this onto operand stack
 1: dup                // duplicate top item on operand stack
 2: astore_2           // store top operand as local variable 2
 3: monitorenter       // enter monitor for top operand
 4: iconst_1           // load 1 to top of operand stack
 5: istore_1           // store top operand as local variable 1
// finally block - no exception
 6: aload_2            // load local variable 2 onto operand stack
 7: monitorexit        // exit monitor for top operand
 8: goto          16   // jump to return
// finally block - after exception
11: astore_3           // store exception as local variable 3
12: aload_2            // load local variable 2 onto operand stack
13: monitorexit        // exit monitor for top operand
14: aload_3            // load local variable 3 (i.e. exception) onto operand stack
15: athrow             // throw top operand (i.e. propagate up the stack)
16: return             // return

The Object methods wait()notify() and notifyAll() used for signaling and control flow control in a synchronised block do not have any special byte codes. Instead these are implemented directly in the JVM as native methods.

TODO - Add diagram for synchronised

method invocation

There are five types of method invocation in the JVM.

invokevirtual
blar blar
invokespecial
blar blar
invokestatic
blar blar
invokeinterface
blar blar
invokedynamic
blar blar
invokehandle
blar blar

TODO - This article is a work in progress and has not yet been published!!

For more detail on the internal architecture in the JVM and different memory areas used during byte code execution see my previous article on JVM Internals

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 JavaScript 编写的记忆游戏(附源代码)   项目:JavaScript 记忆游戏(附源代码) 记忆检查游戏是一个使用 HTML5、CSS 和 JavaScript 开发的简单项目。这个游戏是关于测试你的短期 记忆技能。玩这个游戏 时,一系列图像会出现在一个盒子形状的区域中 。玩家必须找到两个相同的图像并单击它们以使它们消失。 如何运行游戏? 记忆游戏项目仅包含 HTML、CSS 和 JavaScript。谈到此游戏的功能,用户必须单击两个相同的图像才能使它们消失。 点击卡片或按下键盘键,通过 2 乘 2 旋转来重建鸟儿对,并发现隐藏在下面的图像! 如果翻开的牌面相同(一对),您就赢了,并且该对牌将从游戏中消失! 否则,卡片会自动翻面朝下,您需要重新尝试! 该游戏包含大量的 javascript 以确保游戏正常运行。 如何运行该项目? 要运行此游戏,您不需要任何类型的本地服务器,但需要浏览器。我们建议您使用现代浏览器,如 Google Chrome 和 Mozilla Firefox, 以获得更好、更优化的游戏体验。要玩游戏,首先,通过单击 memorygame-index.html 文件在浏览器中打开游戏。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。
使用 JavaScript 编写的 Squareshooter 游戏及其源代码   项目:使用 JavaScript 编写的 Squareshooter 游戏(附源代码) 这款游戏是双人游戏。这是一款使用 JavaScript 编写的射击游戏,带有门户和强化道具。在这里,每个玩家都必须控制方形盒子(作为射手)。这款射击游戏的主要目标是射击对手玩家以求生存。当它射击对手时,它会获得一分。 游戏制作 该游戏仅使用 HTML 和 JavaScript 开发。该游戏的 PC 控制也很简单。 对于玩家 1: T:朝你上次动作的方向射击 A:向左移动 D:向右移动 W:向上移动 S:向下移动 对于玩家2: L:朝你上次移动的方向射击 左箭头:向左移动 右箭头:向右移动 向上箭头:向上移动 向下箭头:向下移动 游戏会一直进行,直到您成功射击对手或对手射击您为止。游戏得分显示在顶部。所有游戏功能均由 JavaScript 设置,而布局和其他次要功能则由 HTML 设置。 如何运行该项目? 要运行此项目,您不需要任何类型的本地服务器,但需要浏览器。我们建议您使用现代浏览器,如 Google Chrome 和 Mozilla Firefox。要运行此游戏,首先,通过单击 index.html 文件在浏览器中打开项目。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值