[英]Why synchronized keyword does not create monitor enter every time
为什么synced关键字每次使用时都不会在字节码级别创建监视器输入?
The synchronized
keyword can be used in two ways: 可以通过两种方式使用synchronized
关键字:
When you use synchronized(obj)
inside the body of a function, the compiler will emit monitorenter
/ monitorexit
bytecodes for the relevant monitor. 当您在函数体内使用synchronized(obj)
,编译器将为相关监视器发出monitorenter
/ monitorexit
字节码。
If the entire method is declared synchronized
, in the bytecodes the method will be marked as ACC_SYNCHRONIZED
. 如果整个方法都声明为已synchronized
,则该方法在字节码中将标记为ACC_SYNCHRONIZED
。 The JVM will implicitly enter and exit the monitor when entering/exiting the method. 进入/退出方法时,JVM将隐式进入和退出监视器。 No monitorenter
/ monitorexit
bytecodes are emitted, nor indeed required. 没有发出monitorenter
/ monitorexit
字节码,也没有要求。
Consider the following two methods: 请考虑以下两种方法:
public class Sync {
public void f() {
synchronized (this) {
}
}
public synchronized void g() {
}
}
They compile to: 他们编译为:
public void f();
Code:
0: aload_0
1: dup
2: monitorenter
3: monitorexit
4: return
public synchronized void g();
Code:
0: return
As you can see, g()
is still marked as synchronized
in the bytecodes, so the JVM knows what to do. 如您所见, g()
在字节码中仍被标记为已synchronized
,因此JVM知道该怎么做。
Disclaimer: This is what my compiler does. 免责声明:这是我的编译器所做的。 It seems possible that a different compiler might chose to emit monitorenter
/ monitorexit
instead of using ACC_SYNCHRONIZED
. 似乎其他编译器可能选择发出monitorenter
/ monitorexit
而不是使用ACC_SYNCHRONIZED
。 Whether any existing compiler does that, I don't know. 我不知道是否存在任何现有的编译器。
synchronized keyword does not create monitor 同步关键字不创建监视器
The mutex or monitor is the object itself. 互斥或监视器是对象本身。 In Java the synchronized
keyword is implicit
locking ie it uses the objects iternal lock for sunchronization 在Java中synchronized
关键字是implicit
锁定,即它采用了对象iternal锁sunchronization
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.