1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.named.hazelcast;
20
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23 import java.util.concurrent.TimeUnit;
24
25 import com.hazelcast.core.HazelcastInstance;
26 import com.hazelcast.cp.ISemaphore;
27 import org.eclipse.aether.named.NamedLock;
28 import org.eclipse.aether.named.NamedLockKey;
29 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock;
30 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock.AdaptedSemaphore;
31 import org.eclipse.aether.named.support.NamedLockFactorySupport;
32
33 import static java.util.Objects.requireNonNull;
34
35
36
37
38
39
40 public class HazelcastSemaphoreNamedLockFactory extends NamedLockFactorySupport {
41 protected final HazelcastInstance hazelcastInstance;
42
43 protected final boolean manageHazelcast;
44
45 private final HazelcastSemaphoreProvider hazelcastSemaphoreProvider;
46
47 private final ConcurrentMap<NamedLockKey, ISemaphore> semaphores;
48
49 public HazelcastSemaphoreNamedLockFactory(
50 final HazelcastInstance hazelcastInstance,
51 final boolean manageHazelcast,
52 final HazelcastSemaphoreProvider hazelcastSemaphoreProvider) {
53 this.hazelcastInstance = requireNonNull(hazelcastInstance);
54 this.manageHazelcast = manageHazelcast;
55 this.hazelcastSemaphoreProvider = requireNonNull(hazelcastSemaphoreProvider);
56 this.semaphores = new ConcurrentHashMap<>();
57 }
58
59 @Override
60 protected AdaptedSemaphoreNamedLock createLock(final NamedLockKey key) {
61 ISemaphore semaphore = semaphores.computeIfAbsent(
62 key, k -> hazelcastSemaphoreProvider.acquireSemaphore(hazelcastInstance, key));
63 return new AdaptedSemaphoreNamedLock(key, this, new HazelcastSemaphore(semaphore));
64 }
65
66 @Override
67 protected void destroyLock(final NamedLock namedLock) {
68 if (namedLock instanceof AdaptedSemaphoreNamedLock) {
69 final NamedLockKey key = namedLock.key();
70 hazelcastSemaphoreProvider.releaseSemaphore(hazelcastInstance, key, semaphores.remove(key));
71 }
72 }
73
74 @Override
75 protected void doShutdown() {
76 if (manageHazelcast) {
77 hazelcastInstance.shutdown();
78 }
79 }
80
81 private static final class HazelcastSemaphore implements AdaptedSemaphore {
82 private final ISemaphore semaphore;
83
84 private HazelcastSemaphore(final ISemaphore semaphore) {
85 this.semaphore = semaphore;
86 }
87
88 @Override
89 public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException {
90 return semaphore.tryAcquire(perms, time, unit);
91 }
92
93 @Override
94 public void release(final int perms) {
95 semaphore.release(perms);
96 }
97 }
98 }