Whenever Java interview, "lock" is bound to be mentioned stuff. So, in the interview, we talk about "lock" will talk about what to do, and whether you Tell me to "lock" enough to understand?
This article aims to analyze the underlying principles of the lock, and lock application scenarios.
一、Synchronized
1, a face questions
Two synchronization methods writer and reader access to the same object in the object are A, B two threads, will produce mutually exclusive?
|
|
答案:会。因为synchronized修饰的是方法,锁是对象锁
,默认当前的对象作为锁的对象。只有当A释放锁之后,B才会获得对象的锁。
(1)如果是换成是不同对象呢?
不会互斥,因为锁的是对象
,而不是方法
。
(2)如果writer、reader方法加上static修饰,两个线程中,类直接调用两个方法呢?
会互斥,因为锁的是Class对象。
(3)如果writer方法用static修饰,reader方法不用呢?
不会互斥。因为一个是对象锁,一个是Class对象锁,锁的类型不同。
synchronized修饰位置与锁的关系:
- 同步方法 —— 对象锁,当前实例对象
- 静态同步方法 —— 类对象锁,当前对象的Class对象
- 同步方法块 —— 对象锁,synchonized括号里配置的对象
二、锁的底层实现
思考几个问题
- 对象锁、Class对象锁时如何实现的
- 为什么要这么设计,只设计一个对象锁或Class对象锁,有什么不好?
1、反编译
|
|
使用javac
和javap -verbose
命令,反编译
上述代码
|
|
同步代码块:使用monitorenter和monitorexit指令实现,通过监听器对象去获得锁
和释放锁
。
同步方法、静态同步方法:使用修饰符ACC_SYNCHRONIZED
实现。
三、锁的形式
Before JDK1.6, synchronized only the traditional locking mechanism.
JDK1.6 introduced two new types of locks: biased locking lock and lightweight. The purpose is to solve the introduction, there is no multi-threaded competition or no competition cases, performance problems caused by traditional lock.
Four states lock: no lock status, tend to lock status, lock status lightweight, heavyweight lock status. Lock can be upgraded, not downgraded.
1, the object head
To unlock the mechanism, we must first understand the object header.
Java object head of Mark Word default storage object HashCode, age and generational lock flag.
Storing Java object header structure is as follows :
Lock status | 25bit | 4bit | 1bit whether it is biased locking | 2bit lock flag |
---|---|---|---|---|
Lock-free status | hashCode object | Generational age of the subject | 0 | 01 |
Mark Word of state changes :
Lock status | 30bit | 2bit |
---|---|---|
Lightweight lock | Pointing the stack pointer record lock | Lock flag 00 |
Heavyweight lock | A pointer pointing mutex | Lock flag 10 |
Lock status | 23bit | 3bit | 3bit | 1bit | 2bit |
---|---|---|---|---|---|
Biased locking | Thread ID | Epoch | Object generational Age | 1 | 01 |
2, biased locking
Because in most cases, there is no lock multithreaded competition, and the total obtained by the same thread several times. In order to lower the cost to acquire a lock is introduced.
3, lightweight lock
Reference Documents
1, JDK8 HotSpot Virtual Machine Source
Original: Big Box On Java lock