What primitive is used to implement the synchronized keyword?

前端 未结 2 490
鱼传尺愫
鱼传尺愫 2021-01-12 05:32

When we use synchronized keyword in java, which synchronization primitive is used exactly? Lock, Semaphore, Monitor, Mutex ?

EDIT :

2条回答
  •  盖世英雄少女心
    2021-01-12 06:15

    From the JLS (§17.1. Synchronization):

    The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.

    Thus "monitor" is the answer to your first question.

    As to the second question, this is an unspecified implementation detail.

提交回复
热议问题