Reduce allocation slightly further

This commit is contained in:
Tony Garnock-Jones 2023-10-28 15:45:27 +02:00
parent f55fd2c668
commit 5401d2d8e9
1 changed files with 15 additions and 13 deletions

View File

@ -8,10 +8,9 @@ import java.util.logging.Logger;
public class Turn {
private final static AtomicLong nextHandle = new AtomicLong(0);
private final static record SinglePending(Actor ac, List<Consumer<Turn>> actions) {}
private final Actor _actor;
private SinglePending _singlePending = null;
private Actor _pendingTarget = null;
private List<Consumer<Turn>> _pendingQ = null;
private Map<Actor, List<Consumer<Turn>>> _pending = null;
private boolean _complete = false;
@ -45,10 +44,11 @@ public class Turn {
if (_pending != null) {
_pending.forEach((ac, q) -> ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t)))));
_pending = null;
} else if (_singlePending != null) {
var ac = _singlePending.ac();
var q = _singlePending.actions();
_singlePending = null;
} else if (_pendingTarget != null) {
var ac = _pendingTarget;
var q = _pendingQ;
_pendingTarget = null;
_pendingQ = null;
ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t))));
}
_complete = true;
@ -63,17 +63,19 @@ public class Turn {
private void enqueue(Actor target, Consumer<Turn> action) {
if (_complete) throw new IllegalStateException("Attempt to reuse a committed Turn");
if (_pending == null) {
if (_singlePending == null) {
_singlePending = new SinglePending(target, singletonList(action));
if (_pendingTarget == null) {
_pendingTarget = target;
_pendingQ = singletonList(action);
return;
}
if (_singlePending.ac() == target) {
_singlePending.actions().add(action);
if (_pendingTarget == target) {
_pendingQ.add(action);
return;
}
_pending = new HashMap<>();
_pending.put(_singlePending.ac(), _singlePending.actions());
_singlePending = null;
_pending.put(_pendingTarget, _pendingQ);
_pendingTarget = null;
_pendingQ = null;
}
_pending.computeIfAbsent(target, k -> new LinkedList<>()).add(action);
}