From 8f6e0240eb89725641abd2605e0742bdf784f8f3 Mon Sep 17 00:00:00 2001 From: TheMode Date: Wed, 21 Apr 2021 14:32:42 +0200 Subject: [PATCH] added new #tryAcquire method with a return value instead of consumer --- .../net/minestom/server/lock/Acquirable.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/net/minestom/server/lock/Acquirable.java b/src/main/java/net/minestom/server/lock/Acquirable.java index d61cf48f0..67c7bd876 100644 --- a/src/main/java/net/minestom/server/lock/Acquirable.java +++ b/src/main/java/net/minestom/server/lock/Acquirable.java @@ -5,6 +5,7 @@ import net.minestom.server.thread.BatchThread; import net.minestom.server.thread.ThreadProvider; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; @@ -83,6 +84,21 @@ public final class Acquirable { return false; } + /** + * Retrieves {@link #unwrap()} only if this element can be safely + * acquired without any synchronization. + * + * @return this element or null if unsafe + */ + public @Nullable T tryAcquire() { + final Thread currentThread = Thread.currentThread(); + final BatchThread elementThread = getHandler().getBatchThread(); + if (Objects.equals(currentThread, elementThread)) { + return unwrap(); + } + return null; + } + /** * Signals the acquisition manager to acquire 'this' at the end of the thread tick. *