mirror of
https://github.com/Minestom/Minestom.git
synced 2024-11-12 13:44:28 +01:00
More safety in Acquired + doc
Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
parent
7b059d2be5
commit
c31aa8a7ec
@ -6,28 +6,39 @@ import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/**
|
||||
* Represents an object that has been safely acquired and can be freed again.
|
||||
* <p>
|
||||
* This class should not be shared, and it is recommended to call {@link #unlock()}
|
||||
* once the acquisition goal has been fulfilled to limit blocking time.
|
||||
*
|
||||
* @param <T> the type of the acquired object
|
||||
*/
|
||||
public final class Acquired<T> {
|
||||
private final T value;
|
||||
private final Thread owner;
|
||||
private final ReentrantLock lock;
|
||||
private boolean unlocked;
|
||||
|
||||
Acquired(T value, TickThread tickThread) {
|
||||
this.value = value;
|
||||
this.lock = AcquirableImpl.enter(Thread.currentThread(), tickThread);
|
||||
this.owner = Thread.currentThread();
|
||||
this.lock = AcquirableImpl.enter(owner, tickThread);
|
||||
}
|
||||
|
||||
public @NotNull T get() {
|
||||
checkLock();
|
||||
safeCheck();
|
||||
return value;
|
||||
}
|
||||
|
||||
public void unlock() {
|
||||
checkLock();
|
||||
safeCheck();
|
||||
this.unlocked = true;
|
||||
AcquirableImpl.leave(lock);
|
||||
}
|
||||
|
||||
private void checkLock() {
|
||||
private void safeCheck() {
|
||||
Check.stateCondition(Thread.currentThread() != owner, "Acquired object is owned by the thread {0}", owner);
|
||||
Check.stateCondition(unlocked, "The acquired element has already been unlocked!");
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user