66
77package modelengine .fit .waterflow .domain .context .repo .flowlock ;
88
9+ import java .util .Map ;
10+ import java .util .concurrent .ConcurrentHashMap ;
11+ import java .util .concurrent .TimeUnit ;
12+ import java .util .concurrent .atomic .AtomicInteger ;
13+ import java .util .concurrent .locks .Condition ;
914import java .util .concurrent .locks .Lock ;
15+ import java .util .concurrent .locks .ReentrantLock ;
1016
1117/**
1218 * 流程锁,内存版本的实现
1521 * @since 1.0
1622 */
1723public class FlowLocksMemo implements FlowLocks {
24+ private final Map <String , MemLockWrapper > locks = new ConcurrentHashMap <>();
25+
26+ @ Override
27+ public Lock getLocalLock (String key ) {
28+ return locks .compute (key , (__ , value ) -> {
29+ if (value == null ) {
30+ return new MemLockWrapper (key , new ReentrantLock (), this );
31+ }
32+ return value ;
33+ });
34+ }
35+
1836 /**
1937 * 获取分布式锁
2038 * 获取分布式锁的key值,一般是prefix-streamID-nodeID-suffixes
@@ -27,4 +45,69 @@ public class FlowLocksMemo implements FlowLocks {
2745 public Lock getDistributeLock (String key ) {
2846 return getLocalLock (key );
2947 }
48+
49+ private void tryCleanLocalLock (String key ) {
50+ this .locks .compute (key , (__ , value ) -> {
51+ if (value == null ) {
52+ return null ;
53+ }
54+ if (value .getRefCount () == 0 ) {
55+ return null ;
56+ }
57+ return value ;
58+ });
59+ }
60+
61+ private static class MemLockWrapper implements Lock {
62+ private final String key ;
63+ private final AtomicInteger refCount = new AtomicInteger (1 );
64+ private final ReentrantLock target ;
65+ private final FlowLocksMemo locksMemo ;
66+
67+ private MemLockWrapper (String key , ReentrantLock target , FlowLocksMemo locksMemo ) {
68+ this .key = key ;
69+ this .target = target ;
70+ this .locksMemo = locksMemo ;
71+ }
72+
73+ @ Override
74+ public void lock () {
75+ this .target .lock ();
76+ }
77+
78+ @ Override
79+ public void lockInterruptibly () throws InterruptedException {
80+ this .target .lockInterruptibly ();
81+ }
82+
83+ @ Override
84+ public boolean tryLock () {
85+ return this .target .tryLock ();
86+ }
87+
88+ @ Override
89+ public boolean tryLock (long time , TimeUnit unit ) throws InterruptedException {
90+ return this .target .tryLock (time , unit );
91+ }
92+
93+ @ Override
94+ public void unlock () {
95+ this .target .unlock ();
96+ this .refCount .decrementAndGet ();
97+ this .locksMemo .tryCleanLocalLock (this .key );
98+ }
99+
100+ @ Override
101+ public Condition newCondition () {
102+ return this .target .newCondition ();
103+ }
104+
105+ private void addRef () {
106+ this .refCount .incrementAndGet ();
107+ }
108+
109+ private int getRefCount () {
110+ return this .refCount .get ();
111+ }
112+ }
30113}
0 commit comments