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.support.AdaptedSemaphoreNamedLock;
28 import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock.AdaptedSemaphore;
29 import org.eclipse.aether.named.support.NamedLockFactorySupport;
30
31 import static java.util.Objects.requireNonNull;
32
33
34
35
36
37
38 public class HazelcastSemaphoreNamedLockFactory extends NamedLockFactorySupport {
39 protected final HazelcastInstance hazelcastInstance;
40
41 protected final boolean manageHazelcast;
42
43 private final HazelcastSemaphoreProvider hazelcastSemaphoreProvider;
44
45 private final ConcurrentMap<String, ISemaphore> semaphores;
46
47 public HazelcastSemaphoreNamedLockFactory(
48 final HazelcastInstance hazelcastInstance,
49 final boolean manageHazelcast,
50 final HazelcastSemaphoreProvider hazelcastSemaphoreProvider) {
51 this.hazelcastInstance = requireNonNull(hazelcastInstance);
52 this.manageHazelcast = manageHazelcast;
53 this.hazelcastSemaphoreProvider = requireNonNull(hazelcastSemaphoreProvider);
54 this.semaphores = new ConcurrentHashMap<>();
55 }
56
57 @Override
58 protected AdaptedSemaphoreNamedLock createLock(final String name) {
59 ISemaphore semaphore = semaphores.computeIfAbsent(
60 name, k -> hazelcastSemaphoreProvider.acquireSemaphore(hazelcastInstance, name));
61 return new AdaptedSemaphoreNamedLock(name, this, new HazelcastSemaphore(semaphore));
62 }
63
64 @Override
65 protected void destroyLock(final String name) {
66 hazelcastSemaphoreProvider.releaseSemaphore(hazelcastInstance, name, semaphores.remove(name));
67 }
68
69 @Override
70 public void shutdown() {
71 if (manageHazelcast) {
72 hazelcastInstance.shutdown();
73 }
74 }
75
76 private static final class HazelcastSemaphore implements AdaptedSemaphore {
77 private final ISemaphore semaphore;
78
79 private HazelcastSemaphore(final ISemaphore semaphore) {
80 this.semaphore = semaphore;
81 }
82
83 @Override
84 public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException {
85 return semaphore.tryAcquire(perms, time, unit);
86 }
87
88 @Override
89 public void release(final int perms) {
90 semaphore.release(perms);
91 }
92 }
93 }