-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModifyLockState.java
43 lines (37 loc) · 1.93 KB
/
ModifyLockState.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package org.mtokarski.object.header.lock;
import org.mtokarski.object.header.HeaderUtil;
/**
* "Unlocking" object in synchronised block allows other thread to acquire lock.
* This code without modifying header would cause a dead lock.
*/
public class ModifyLockState {
public static void main(String[] args) throws InterruptedException {
Object o = new Object();
System.out.println("Object hash at the beginning: " + o.hashCode());
System.out.println();
synchronized (o) {
System.out.println("Object is " + HeaderUtil.extractLockState(o));
long originalHeader = HeaderUtil.setUnlocked(o);
System.out.println("Original header: " + Long.toBinaryString(originalHeader));
System.out.println("Header after \"unlocking\": " + Long.toBinaryString(HeaderUtil.getObjectHeader(o)));
System.out.println("Object is " + HeaderUtil.extractLockState(o));
System.out.println("Object hash: " + o.hashCode());
System.out.println();
Thread thread = new Thread(() -> {
synchronized (o) {
System.out.println("Header in thread's synchronised block: " + Long.toBinaryString(HeaderUtil.getObjectHeader(o)));
System.out.println("Displaced header in thread's synchronised block: " + Long.toBinaryString(HeaderUtil.getDisplacedHeader(o)));
System.out.println("Object hash: " + o.hashCode());
System.out.println();
}
});
thread.start();
thread.join();
System.out.println("Header after thread execution: " + Long.toBinaryString(HeaderUtil.getObjectHeader(o)));
System.out.println();
//without setting back valid header, application doesn't terminate
HeaderUtil.setHeader(o, originalHeader);
}
System.out.println("Object hash: " + o.hashCode());
}
}