1 package org.eclipse.aether.named.hazelcast;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import com.hazelcast.core.HazelcastInstance;
23 import com.hazelcast.cp.ISemaphore;
24 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock;
25 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock.AdaptedSemaphore;
26 import org.eclipse.aether.named.support.NamedLockFactorySupport;
27 import org.eclipse.aether.named.support.NamedLockSupport;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.TimeUnit;
31 import java.util.function.BiFunction;
32
33
34
35
36
37 public class HazelcastSemaphoreNamedLockFactory
38 extends NamedLockFactorySupport
39 {
40 protected static final String NAME_PREFIX = "maven:resolver:";
41
42 private final HazelcastInstance hazelcastInstance;
43
44 private final BiFunction<HazelcastInstance, String, ISemaphore> semaphoreFunction;
45
46 private final boolean destroySemaphore;
47
48 private final boolean manageHazelcast;
49
50 private final ConcurrentHashMap<String, ISemaphore> semaphores;
51
52 public HazelcastSemaphoreNamedLockFactory(
53 final HazelcastInstance hazelcastInstance,
54 final BiFunction<HazelcastInstance, String, ISemaphore> semaphoreFunction,
55 final boolean destroySemaphore,
56 final boolean manageHazelcast
57 )
58 {
59 this.hazelcastInstance = hazelcastInstance;
60 this.semaphoreFunction = semaphoreFunction;
61 this.destroySemaphore = destroySemaphore;
62 this.manageHazelcast = manageHazelcast;
63 this.semaphores = new ConcurrentHashMap<>();
64 }
65
66 @Override
67 protected NamedLockSupport createLock( final String name )
68 {
69 ISemaphore semaphore = semaphores.computeIfAbsent(
70 name, k -> semaphoreFunction.apply( hazelcastInstance, k )
71 );
72 return new AdaptedSemaphoreNamedLock( name, this, new HazelcastSemaphore( semaphore ) );
73 }
74
75 @Override
76 public void shutdown()
77 {
78 if ( manageHazelcast )
79 {
80 hazelcastInstance.shutdown();
81 }
82 }
83
84 @Override
85 protected void destroyLock( final NamedLockSupport lock )
86 {
87 ISemaphore semaphore = semaphores.remove( lock.name() );
88 if ( destroySemaphore )
89 {
90 semaphore.destroy();
91 }
92 }
93
94 private static final class HazelcastSemaphore implements AdaptedSemaphore
95 {
96 private final ISemaphore semaphore;
97
98 private HazelcastSemaphore( final ISemaphore semaphore )
99 {
100 semaphore.init( Integer.MAX_VALUE );
101 this.semaphore = semaphore;
102 }
103
104 @Override
105 public boolean tryAcquire( final int perms, final long time, final TimeUnit unit )
106 throws InterruptedException
107 {
108 return semaphore.tryAcquire( perms, time, unit );
109 }
110
111 @Override
112 public void release( final int perms )
113 {
114 semaphore.release( perms );
115 }
116 }
117 }