Re-added acquired to support manual locking

This commit is contained in:
TheMode 2021-04-24 18:25:15 +02:00
parent 845a8608db
commit 0043cc7275
2 changed files with 44 additions and 0 deletions

View File

@ -53,6 +53,18 @@ public interface Acquirable<T> {
AsyncUtils.runAsync(() -> sync(consumer));
}
default @NotNull Acquired<T> lock() {
var optional = optional();
if (optional.isPresent()) {
return new Acquired<>(optional.get(), false, null);
} else {
final Thread currentThread = Thread.currentThread();
final TickThread tickThread = getHandler().getTickThread();
var lock = Acquisition.acquireEnter(currentThread, tickThread);
return new Acquired<>(unwrap(), true, lock);
}
}
default @NotNull Optional<T> optional() {
final Thread currentThread = Thread.currentThread();
final TickThread tickThread = getHandler().getTickThread();

View File

@ -0,0 +1,32 @@
package net.minestom.server.acquirable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.locks.ReentrantLock;
public class Acquired<T> {
private final T value;
private final boolean locked;
private final ReentrantLock lock;
protected Acquired(@NotNull T value,
boolean locked, @Nullable ReentrantLock lock) {
this.value = value;
this.locked = locked;
this.lock = lock;
}
public @NotNull T get() {
return value;
}
public void unlock() {
if (!locked)
return;
Acquisition.acquireLeave(lock);
}
}