/* * Copyright 2021 Jonathan Lindegaard Starup * * Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE.md file. */////// Type of reentrant mutual exclusion locks, and its functions.///pubmod Concurrent.ReentrantLock {import java.util.concurrent.TimeUnitimport java.lang.InterruptedExceptionimport java.lang.IllegalMonitorStateExceptionimport java.util.concurrent.locks.{ReentrantLock => JReentrantLock}use Concurrent.Conditionuse Concurrent.Condition.Condition////// Type of reentrant mutual exclusion locks.////// Wraps a Java `ReentrantLock`.///pubenumReentrantLock(JReentrantLock)////// Creates an instance of ReentrantLock with the given fairness policy./// `fair = False` is the default for Java.///pubdefnewLock(fair: Bool): ReentrantLock \ IO = ReentrantLock(new JReentrantLock(fair))////// Returns true if this lock has fairness set true.///pubdefisFair(lock: ReentrantLock): Bool \ {} =let ReentrantLock(l) = lock;l.isFair()////// Acquires the lock.///pubdeflock(lock: ReentrantLock): Unit \ IO =let ReentrantLock(l) = lock;l.lock()////// Acquires the lock unless the current thread is interrupted.///pubdeflockInterruptibly(lock: ReentrantLock): Result[InterruptedException, Unit] \ IO =let ReentrantLock(l) = lock;try { Ok(l.lockInterruptibly()) } catch {casee: InterruptedException => Err(e) }////// Returns a Condition instance for use with this Lock instance.///pubdefnewCondition(lock: ReentrantLock): Condition \ IO =let ReentrantLock(l) = lock; Condition(l.newCondition())////// Acquires the lock only if it is not held by another thread at the time of invocation.///pubdeftryLock(lock: ReentrantLock): Bool \ IO =let ReentrantLock(l) = lock;l.tryLock()////// Acquires the lock if it is not held by another thread within the given waiting time (nanos) and the current thread has not been interrupted.///pubdeftryLockNanos(lock: ReentrantLock, nanosTimeout: Int64): Result[InterruptedException, Bool] \ IO =let ReentrantLock(l) = lock;try { Ok(l.tryLock(nanosTimeout, TimeUnit.NANOSECONDS)) } catch {casee: InterruptedException => Err(e) }////// Attempts to release this lock.///pubdefunlock(lock: ReentrantLock): Result[IllegalMonitorStateException, Unit] \ IO =let ReentrantLock(l) = lock;try { Ok(l.unlock()) } catch {casee: IllegalMonitorStateException => Err(e) }}