Archived
0

PoorMansLock implementation

This commit is contained in:
Daniil
2018-08-05 13:09:54 +07:00
parent 32fa42bdc3
commit afe88e260c
2 changed files with 58 additions and 4 deletions

View File

@@ -1,6 +1,9 @@
package mc.core.events.api.samples; package mc.core.events.api.samples;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import mc.core.Location; import mc.core.Location;
import mc.core.block.Block;
import mc.core.events.EventBase; import mc.core.events.EventBase;
import mc.core.events.api.interfaces.LocationProvidingEvent; import mc.core.events.api.interfaces.LocationProvidingEvent;
import mc.core.events.api.interfaces.PlayerProvidingEvent; import mc.core.events.api.interfaces.PlayerProvidingEvent;
@@ -10,10 +13,11 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@RequiredArgsConstructor
@Getter
public class BlockBreakEvent extends EventBase implements PlayerProvidingEvent, LocationProvidingEvent { public class BlockBreakEvent extends EventBase implements PlayerProvidingEvent, LocationProvidingEvent {
private Player player; private final Player player;
// TODO: There should be a proper block reference private final Block block;
private Location blockLocation;
@Override @Override
@@ -23,6 +27,6 @@ public class BlockBreakEvent extends EventBase implements PlayerProvidingEvent,
@Override @Override
public Collection<Location> getAssociatedLocations() { public Collection<Location> getAssociatedLocations() {
return Collections.singletonList(blockLocation); return Collections.singletonList(block.getLocation());
} }
} }

View File

@@ -0,0 +1,50 @@
package mc.core.events.lock;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
public class PoorMansLock {
private Thread owner = null;
private Set<Consumer<PoorMansLock>> callbacks = new CopyOnWriteArraySet<>();
public void addCallback(Consumer<PoorMansLock> callback) {
callbacks.add(callback);
}
public void removeCallback(Consumer<PoorMansLock> callback) {
callbacks.remove(callback);
}
public boolean isLocked() {
return owner != null;
}
private void triggerUpdate() {
for (Consumer<PoorMansLock> consumer : callbacks)
consumer.accept(this);
}
public synchronized void lock() {
if (owner != null && owner != Thread.currentThread()) {
// ToDo: do we need to await for unlock?
throw new RuntimeException("Unable to lock this resource: already in use");
}
owner = Thread.currentThread();
triggerUpdate();
}
public synchronized void unlock() {
if (owner == null)
return;
if (owner != Thread.currentThread()) {
throw new RuntimeException("Attempt to unlock resource from non-owning thread");
}
owner = null;
triggerUpdate();
}
}