synchronized同步方法的字节码还原
method_info {
u2 access_flags;
u2 name_index;
u2 descriptor_index;
u2 attributes_count;
attribute_info attributes[attributes_count];
}
// Account.java
public synchronized void setBalance(double balance) {
this.balance = balance;
}
## 上述代码的字节码如下
public synchronized void setBalance(double);
descriptor: (D)V
flags: ACC_PUBLIC, ACC_SYNCHRONIZED
Code:
stack=3, locals=3, args_size=2
0: aload_0
1: dload_1
2: putfield #2 // Field balance:D
5: return
LineNumberTable:
line 20: 0
line 21: 5
LocalVariableTable:
Start Length Slot Name Signature
0 6 0 this Lcom/xiaokunliu/concurrency/sync/syncmethod/Account;
0 6 1 balance D
## 从字节码中可以看出在方法添加synchronized关键字,会在编译阶段多产生一个flag,即ACC_SYNCHRONIZED
synchronized同步方法的本质
1) Method-level synchronization is performed implicitly, as part of method invocation and return.
2) A synchronized method is distinguished in the run-time constant pool's method_info structure by the ACC_SYNCHRONIZED flag, which is checked by the method invocation instructions.
3) When invoking a method for which ACC_SYNCHRONIZED is set, the executing thread enters a monitor, invokes the method itself, and exits the monitor whether the method invocation completes normally or abruptly.
4) During the time the executing thread owns the monitor, no other thread may enter it. If an exception is thrown during invocation of the synchronized method and the synchronized method does not handle the exception, the monitor for the method is automatically exited before the exception is rethrown out of the synchronized method
1) 方法级同步在JVM中是隐式执行的,是作为方法调用和返回的一部分
2) 同步方法在运行时常量池的method_info结构中由ACC_SYNCHRONIZED标志加以区分,该标志由方法调用指令进行检查
3) 执行线程识别到方法中含有ACC_SYNCHRONIZED标志将会获取一个监视器对象然后调用方法,最后而且不论当线程正常执行或是异常退出时将会释放监视器对象
4) 在执行期间,执行线程持有监视器对象,而其他执行线程将无法获取监视器对象,如果方法抛处异常将会释放监视器对象
synchronized同步代码块字节码还原
System.out.println(Thread.currentThread().getName() + " get controlCinema1 lock, add number is " + number);
53: monitorexit
synchronized同步代码块的工作原理
1) Synchronization of sequences of instructions is typically used to encode the synchronized block of the Java programming language.
2) The Java Virtual Machine supplies the monitorenter and monitorexit instructions to support such language constructs.
3) Proper implementation of synchronized blocks requires cooperation from a compiler targeting the Java Virtual Machine
1) 指令序列的同步通常用于java程序中的同步代码块
2) jvm支持在编译阶段执行同步指令
3) 同步块的实现需要java编译器的支持
结构化锁
结构化锁定是这样一种情况:在方法调用期间,给定监控器上的每个出口与该监控器上的前一个入口匹配。
由于不能保证提交给Java虚拟机的所有代码都将执行结构化锁定,所以允许Java虚拟机的实现
工作原理本质
注意点