Why synchronized keyword does not create monitor enter at byte code level every time I use it?
Why synchronized keyword does not create monitor enter at byte code level every time
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
synchronizedkeyword can be used in two ways:When you use
synchronized(obj)inside the body of a function, the compiler will emitmonitorenter/monitorexitbytecodes for the relevant monitor.If the entire method is declared
synchronized, in the bytecodes the method will be marked asACC_SYNCHRONIZED. The JVM will implicitly enter and exit the monitor when entering/exiting the method. Nomonitorenter/monitorexitbytecodes are emitted, nor indeed required.Consider the following two methods:
They compile to:
As you can see,
g()is still marked assynchronizedin the bytecodes, so the JVM knows what to do.Disclaimer: This is what my compiler does. It seems possible that a different compiler might chose to emit
monitorenter/monitorexitinstead of usingACC_SYNCHRONIZED. Whether any existing compiler does that, I don’t know.