diff options
Diffstat (limited to 'vespajlib/src/main/java/com/yahoo/concurrent/lock/Locking.java')
-rw-r--r-- | vespajlib/src/main/java/com/yahoo/concurrent/lock/Locking.java | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/vespajlib/src/main/java/com/yahoo/concurrent/lock/Locking.java b/vespajlib/src/main/java/com/yahoo/concurrent/lock/Locking.java new file mode 100644 index 00000000000..cbfadf73a32 --- /dev/null +++ b/vespajlib/src/main/java/com/yahoo/concurrent/lock/Locking.java @@ -0,0 +1,30 @@ +package com.yahoo.concurrent.lock; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author valerijf + */ +public class Locking { + private final Map<Class<?>, ReentrantLock> locks = new ConcurrentHashMap<>(); + + /** + * Locks class. This will block until the lock is acquired. + * Users of this <b>must</b> close any lock acquired. + * + * @param key the key to lock + * @return the acquired lock + */ + public Lock lock(Class<?> key) { + try { + ReentrantLock lock = locks.computeIfAbsent(key, k -> new ReentrantLock(true)); + lock.tryLock(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + return new Lock(lock); + } catch (InterruptedException e) { + throw new RuntimeException("Interrupted while waiting for lock of " + key); + } + } +} |