简体   繁体   中英

How does Java implement lock

I often use some Java mechanism for handling multithreading problem such as AtomicInteger , synchronized ...

My question is: How Java can implement those lock mechanism? My mean is: when implementing, Java will meet multithreading problem too, and how can they deal with. Does all operating system have lock mechanism and Java just simply call their API.

The implementation of locks in Java is specific to the instruction set of the Java platform. For example, with x86, it might use the CMPXCHG instruction - atomic compare and exchange - at the lowest level to implement the fast path of the lock. The CMPXCHG instruction is a compare-and-swap instruction that guarantees atomic memory access at the hardware level.

If the thread cannot acquire the lock immediately, then it could "spinlock" or it could perform a syscall to schedule a different thread. Different strategies are used depending on the platform, JVM switches, etcetera.


Note that in any language that implements (efficient) locking, there is a bit of "black magic" to implement it. This could be an assembler coded library, or some smarts in the native code compiler that knows to inject special instructions for certain bytecodes or "intrinsic" method calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM