1. public class MCSLock {
2. private static Unsafe unsafe = null;
3. volatile MCSNode tail;
4. private static final long valueOffset;
5.
6. public static class MCSNode {
7. MCSNode next;
8. volatile boolean spin = true;
9. }
10.
11. static {
12. try {
13. unsafe = getUnsafeInstance();
14. valueOffset = unsafe.objectFieldOffset(MCSLock.class.getDeclaredField("tail"));
15. } catch (Exception ex) {
16. throw new Error(ex);
17. }
18. }
19.
20. private static Unsafe getUnsafeInstance() throws Exception {
21. Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
22. theUnsafeInstance.setAccessible(true);
23. return (Unsafe) theUnsafeInstance.get(Unsafe.class);
24. }
25.
26. public void lock(MCSNode currentThreadMcsNode) {
27. MCSNode predecessor = null;
28. for (;;) {
29. predecessor = tail;
30. if (unsafe.compareAndSwapObject(this, valueOffset, tail, currentThreadMcsNode))
31. break;
32. }
33. if (predecessor != null) {
34. predecessor.next = currentThreadMcsNode;
35. while (currentThreadMcsNode.spin) {
36. }
37. }
38. }
39.
40. public void unlock(MCSNode currentThreadMcsNode) {
41. if (tail != currentThreadMcsNode) {
42. if (currentThreadMcsNode.next == null) {
43. if (unsafe.compareAndSwapObject(this, valueOffset, currentThreadMcsNode, null)) {
44. return;
45. } else {
46. while (currentThreadMcsNode.next == null) {
47. }
48. }
49. }
50. currentThreadMcsNode.next.spin = false;
51. }
52. }
}
更多JAVA并发原理剖析请关注下面的专栏 。
作者简介:笔名seaboat,擅长人工智能、计算机科学、数学原理、基础算法 。出版书籍:《图解数据结构与算法》、《Tomcat内核设计剖析》、《人工智能原理科普》 。
推荐阅读
- 5种python方法实现冒泡排序可视化:Bubble Sort Visualizer
- 你们要的MyCat实现MySQL分库分表来了
- 宕机后,Redis如何实现快速恢复?
- 网址太长?轻松搭建自己的短网址平台Shortny v2.0.1源码搭建教程
- 一文搞定 Koa 中间件实现原理
- 如何有效提臀呢?
- 怎样自己在家练瑜伽呢
- 男性自己可以练瑜伽吗
- 自己在家练瑜伽可以吗
- 如何快速增强肌肉力量?