This is an automated email from the ASF dual-hosted git repository.
tabish121 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-protonj2.git
The following commit(s) were added to refs/heads/main by this push:
new 42c4038f PROTON-3006 Cleanup and fix some edge cases in the unsettled
map
42c4038f is described below
commit 42c4038fb740a57c0014cdf7c6a1f0d968880c8b
Author: Timothy Bish <[email protected]>
AuthorDate: Wed Nov 18 19:14:20 2026 -0500
PROTON-3006 Cleanup and fix some edge cases in the unsettled map
Fix some cases where the unsettled map does not behave as a standard map
where
it could actually do so. Fix some edge cases around iterator removes and
ranged
for each and remove each APIs. Removes allocations from the iterator
traversal
and add some cleanups around the ranged disposition cases
---
.../qpid/protonj2/engine/impl/ProtonReceiver.java | 23 +-
.../qpid/protonj2/engine/impl/ProtonSender.java | 23 +-
.../qpid/protonj2/engine/util/UnsettledMap.java | 434 +++++++---
.../protonj2/engine/util/UnsettledMapTest.java | 894 ++++++++++++++++++++-
4 files changed, 1214 insertions(+), 160 deletions(-)
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonReceiver.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonReceiver.java
index 76834b2a..107634ee 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonReceiver.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonReceiver.java
@@ -19,7 +19,7 @@ package org.apache.qpid.protonj2.engine.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.List;
+import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
@@ -32,7 +32,6 @@ import org.apache.qpid.protonj2.engine.Session;
import org.apache.qpid.protonj2.engine.exceptions.ProtocolViolationException;
import org.apache.qpid.protonj2.engine.util.DeliveryIdTracker;
import org.apache.qpid.protonj2.engine.util.UnsettledMap;
-import org.apache.qpid.protonj2.types.UnsignedInteger;
import org.apache.qpid.protonj2.types.transport.Attach;
import org.apache.qpid.protonj2.types.transport.DeliveryState;
import org.apache.qpid.protonj2.types.transport.Detach;
@@ -173,29 +172,33 @@ public class ProtonReceiver extends ProtonLink<Receiver>
implements Receiver {
return drainStateSnapshot != null;
}
- @SuppressWarnings("unchecked")
@Override
public Receiver disposition(Predicate<IncomingDelivery> filter,
DeliveryState disposition, boolean settle) {
checkLinkOperable("Cannot apply disposition");
Objects.requireNonNull(filter, "Supplied filter cannot be null");
- List<UnsignedInteger> toRemove = settle ? new ArrayList<>() :
Collections.EMPTY_LIST;
+ // Walk the unsettled deliveries directly and drop settled entries
through the iterator as
+ // that avoids boxing every delivery id just to visit the entries and
then searching the map
+ // a second time for each delivery that is removed when it is settled.
+ Iterator<ProtonIncomingDelivery> unsettledDeliveries =
unsettled.values().iterator();
+
+ while (unsettledDeliveries.hasNext()) {
+ ProtonIncomingDelivery delivery = unsettledDeliveries.next();
- unsettled.forEach((deliveryId, delivery) -> {
if (filter.test(delivery)) {
if (disposition != null) {
delivery.localState(disposition);
}
if (settle) {
delivery.locallySettled();
- toRemove.add(deliveryId);
}
+
sessionWindow.processDisposition(this, delivery);
- }
- });
- if (!toRemove.isEmpty()) {
- toRemove.forEach(deliveryId -> unsettled.remove(deliveryId));
+ if (settle) {
+ unsettledDeliveries.remove();
+ }
+ }
}
return this;
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonSender.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonSender.java
index e8839699..bde151a2 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonSender.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/impl/ProtonSender.java
@@ -19,7 +19,7 @@ package org.apache.qpid.protonj2.engine.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.List;
+import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
@@ -31,7 +31,6 @@ import org.apache.qpid.protonj2.engine.Sender;
import org.apache.qpid.protonj2.engine.Session;
import org.apache.qpid.protonj2.engine.util.DeliveryIdTracker;
import org.apache.qpid.protonj2.engine.util.UnsettledMap;
-import org.apache.qpid.protonj2.types.UnsignedInteger;
import org.apache.qpid.protonj2.types.transport.Attach;
import org.apache.qpid.protonj2.types.transport.DeliveryState;
import org.apache.qpid.protonj2.types.transport.Detach;
@@ -116,29 +115,33 @@ public class ProtonSender extends ProtonLink<Sender>
implements Sender {
return this;
}
- @SuppressWarnings("unchecked")
@Override
public Sender disposition(Predicate<OutgoingDelivery> filter,
DeliveryState state, boolean settle) {
checkLinkOperable("Cannot apply disposition");
Objects.requireNonNull(filter, "Supplied filter cannot be null");
- List<UnsignedInteger> toRemove = settle ? new ArrayList<>() :
Collections.EMPTY_LIST;
+ // Walk the unsettled deliveries directly and drop settled entries
through the iterator as
+ // that avoids boxing every delivery id just to visit the entries and
then searching the map
+ // a second time for each delivery that is removed when it is settled.
+ Iterator<ProtonOutgoingDelivery> unsettledDeliveries =
unsettled.values().iterator();
+
+ while (unsettledDeliveries.hasNext()) {
+ ProtonOutgoingDelivery delivery = unsettledDeliveries.next();
- unsettled.forEach((deliveryId, delivery) -> {
if (filter.test(delivery)) {
if (state != null) {
delivery.localState(state);
}
if (settle) {
delivery.locallySettled();
- toRemove.add(deliveryId);
}
+
sessionWindow.processDisposition(this, delivery);
- }
- });
- if (!toRemove.isEmpty()) {
- toRemove.forEach(deliveryId -> unsettled.remove(deliveryId));
+ if (settle) {
+ unsettledDeliveries.remove();
+ }
+ }
}
return this;
diff --git
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/util/UnsettledMap.java
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/util/UnsettledMap.java
index 740e1744..e4d0e26e 100644
---
a/protonj2/src/main/java/org/apache/qpid/protonj2/engine/util/UnsettledMap.java
+++
b/protonj2/src/main/java/org/apache/qpid/protonj2/engine/util/UnsettledMap.java
@@ -35,19 +35,24 @@ import org.apache.qpid.protonj2.types.UnsignedInteger;
/**
* A specialized collection like entity that is used to keep track of unsettled
* incoming and outgoing deliveries for AMQP links and the sessions that manage
- * those links.
+ * those links. This {@link Map} type is not thread safe and its behavior is
not
+ * specified if used in a thread un-safe manner. This {@link Map} type does not
+ * support null Deliveries and will throw if any put operation attempts to add
one.
* <p>
* While this class implements the {@link Map} interface it does not fully
behave
* as a standard map as it solves the issue of tracking delivery IDs which
always
* increase until such time as the unsigned integer value used to represent
them
* overflows. It is possible (although unlikely) for the same ID to exist for
multiple
* deliveries if an older delivery exists in the Map and the delivery IDs
overflow and
- * the same value is produced once again.
+ * the same value is produced once again. APIs like {@link #keySet} would
return
+ * duplicate values when multiple deliveries with the same ID exist due to
overflows
+ * although that is unlikely in typical operations.
*
* @param <Delivery> The delivery type being tracked (incoming or outgoing)
*/
-public class UnsettledMap<Delivery> implements Map<UnsignedInteger, Delivery> {
+public final class UnsettledMap<Delivery> implements Map<UnsignedInteger,
Delivery> {
+ @FunctionalInterface
public interface UnsettledGetDeliveryId<Delivery> {
int getDeliveryId(Delivery delivery);
}
@@ -57,17 +62,21 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
private static final int UNSETTLED_INITIAL_BUCKETS = 2;
private static final int UNSETTLED_BUCKET_SIZE = 256;
- // Allow the free list to grow as needed but establish a maximum size
before
- // recycled buckets are allowed to be garbage collected once no longer
used.
- private static final int FREE_LIST_GROWTH_AMOUNT = 2;
+ // Recycled buckets are pooled for reuse but only up to a maximum size,
once that many
+ // buckets are held any surplus is allowed to be garbage collected as it
is no longer used.
+ // The limit is set to cover a map that has grown to a couple of thousand
deliveries so that
+ // refilling such a map after it is emptied needs no new buckets at all.
private static final int FREE_LIST_SIZE_LIMIT = 8;
- // Always full buckets used in operations that needs unwritable bounds
- private final UnsettledBucket<Delivery> ALWAYS_FULL_BUCKET = new
UnsettledBucket<>();
+ // Always full buckets used in operations that needs unwritable bounds use
this version
+ // which has no capacity and cannot be modified.
+ @SuppressWarnings("rawtypes")
+ private static final UnsettledBucket ALWAYS_FULL_BUCKET = new
UnsettledBucket<>();
private final UnsettledGetDeliveryId<Delivery> deliveryIdSupplier;
private final int bucketCapacity;
private final int bucketLowWaterMark;
+ private final int initialBucketCount;
private int size;
private int modCount;
@@ -87,10 +96,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
public UnsettledMap(UnsettledGetDeliveryId<Delivery> idSupplier, int
initialBuckets, int bucketSize) {
- this.deliveryIdSupplier = idSupplier;
- this.bucketCapacity = bucketSize;
- this.bucketLowWaterMark = (int) (bucketSize *
BUCKET_LOAD_FACTOR_MULTIPLIER);
- this.freeListSize = initialBuckets;
+ Objects.requireNonNull(idSupplier, "The ID supplier cannot be null");
if (bucketSize < 1) {
throw new IllegalArgumentException("The bucket size must be
greater than zero");
@@ -100,13 +106,10 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
throw new IllegalArgumentException("The initial number of buckets
must be at least 1");
}
- // All initial buckets go onto the free list
- free = new UnsettledBucket<Delivery>(bucketCapacity);
- for (int i = 1; i < initialBuckets; ++i) {
- UnsettledBucket<Delivery> newFree = new
UnsettledBucket<>(bucketCapacity);
- newFree.prev = free;
- free = newFree;
- }
+ this.deliveryIdSupplier = idSupplier;
+ this.bucketCapacity = bucketSize;
+ this.bucketLowWaterMark = (int) (bucketSize *
BUCKET_LOAD_FACTOR_MULTIPLIER);
+ this.initialBucketCount = initialBuckets;
}
@Override
@@ -116,17 +119,21 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public void clear() {
- for (UnsettledBucket<Delivery> bucket = tail; bucket != null; bucket =
bucket.next) {
- bucket.clear();
+ for (UnsettledBucket<Delivery> bucket = tail; bucket != null;) {
+ final UnsettledBucket<Delivery> current = bucket;
+ bucket = bucket.next;
+
+ current.clear();
if (freeListSize < FREE_LIST_SIZE_LIMIT) {
- bucket.prev = free;
- free = bucket;
+ current.prev = free;
+ free = current;
freeListSize++;
}
}
head = tail = null;
size = 0;
+ generations = 0;
modCount++;
}
@@ -151,20 +158,26 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
* @return <code>null</code> in all cases as this Map type does not check
for duplicates.
*/
public Delivery put(int deliveryId, Delivery delivery) {
+ Objects.requireNonNull(delivery, "The Delivery cannot be null");
+
UnsettledBucket<Delivery> bucket = this.head;
if (bucket != null) {
+ int currentGen = bucket.generation;
+
if (Integer.compareUnsigned(deliveryId, bucket.highestDeliveryId)
<= 0) {
- generations = Math.max(0, generations + 1);
+ generations++;
bucket = advanceHead();
+ bucket.generation = ++currentGen;
} else if (bucket.getFreeSpace() == 0) {
bucket = advanceHead();
+ bucket.generation = currentGen;
}
} else {
bucket = advanceHead();
+ bucket.generation = 0;
}
- bucket.generation = generations;
bucket.put(deliveryId, delivery);
size++;
modCount++;
@@ -184,7 +197,15 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public Delivery get(Object key) {
- if (key instanceof Number number) {
+ if (key instanceof Long number) {
+ if (number < 0 || number.longValue() >
UnsignedInteger.MAX_VALUE.longValue()) {
+ return null;
+ }
+
+ return get(number.intValue());
+ } else if (key instanceof UnsignedInteger number) {
+ return get(number.intValue());
+ } else if (key instanceof Integer number) {
return get(number.intValue());
} else {
return null;
@@ -196,12 +217,20 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
public Delivery get(int deliveryId) {
- return findDelivery(deliveryId, false);
+ return size > 0 ? findDelivery(deliveryId, false) : null;
}
@Override
public Delivery remove(Object key) {
- if (key instanceof Number number) {
+ if (key instanceof Long number) {
+ if (number < 0 || number.longValue() >
UnsignedInteger.MAX_VALUE.longValue()) {
+ return null;
+ }
+
+ return remove(number.intValue());
+ } else if (key instanceof UnsignedInteger number) {
+ return remove(number.intValue());
+ } else if (key instanceof Integer number) {
return remove(number.intValue());
} else {
return null;
@@ -213,12 +242,20 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
public Delivery remove(int deliveryId) {
- return findDelivery(deliveryId, true);
+ return size > 0 ? findDelivery(deliveryId, true) : null;
}
@Override
public boolean containsKey(Object key) {
- if (key instanceof Number number) {
+ if (key instanceof Long number) {
+ if (number < 0 || number.longValue() >
UnsignedInteger.MAX_VALUE.longValue()) {
+ return false;
+ }
+
+ return containsKey(number.intValue());
+ } else if (key instanceof UnsignedInteger number) {
+ return containsKey(number.intValue());
+ } else if (key instanceof Integer number) {
return containsKey(number.intValue());
} else {
return false;
@@ -230,7 +267,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
public boolean containsKey(int deliveryId) {
- return findDelivery(deliveryId, false) != null;
+ return size > 0 && findDelivery(deliveryId, false) != null;
}
@Override
@@ -265,12 +302,18 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
return;
}
+ final int expectedModCount = modCount;
+
for (UnsettledBucket<Delivery> bucket = tail; bucket != null; bucket =
bucket.next) {
final int writeOffset = bucket.writeOffset;
final Delivery[] deliveries = bucket.deliveries;
for (int j = bucket.readOffset; j < writeOffset; ++j) {
action.accept(deliveries[j]);
+
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException("Map was
modified during entry iteration");
+ }
}
}
}
@@ -287,6 +330,8 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
* The upper bound of the last entry to visit.
* @param action
* The action to invoke on each visited entry.
+ *
+ * @throws ConcurrentModificationException if the {@link Map} is modified
by the provided action
*/
public void forEach(int first, int last, Consumer<Delivery> action) {
Objects.requireNonNull(action);
@@ -303,16 +348,25 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
final UnsettledBucket<Delivery> nextGeneration =
forEachInRange(tail, false, first,
UnsignedInteger.MAX_VALUE.intValue(), action);
+ // If the search found entries that matched the range then we can
continue at the
+ // generation boundary and try and match the range after the
overflow, If it did
+ // not match any range then we assume that the front half refers
to a range that
+ // has already been removed and we start from the oldest elements
again to try and
+ // satisfy the range portion after the overflow.
if (nextGeneration != null) {
forEachInRange(nextGeneration, true, 0, last, action);
+ } else {
+ forEachInRange(tail, true, 0, last, action);
}
}
}
- private UnsettledBucket<Delivery> forEachInRange(UnsettledBucket<Delivery>
tail, boolean continuation, int first, int last, Consumer<Delivery> action) {
+ private UnsettledBucket<Delivery> forEachInRange(UnsettledBucket<Delivery>
tail, boolean boundToGeneration, int first, int last, Consumer<Delivery>
action) {
+ final int expectedModCount = modCount;
+
boolean foundFirst = false;
boolean foundLast = false;
- int inGeneration = continuation ? tail.generation : -1;
+ int currentGeneration = tail.generation;
UnsettledBucket<Delivery> bucket = tail;
@@ -321,13 +375,15 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
int readStart = bucket.readOffset;
- // We are locked to a ranged search in a single generation so if
values
- // jump we can stop and return where the next generation starts in
case
- // the caller has a second range to check.
- if (inGeneration >= 0 && bucket.generation != inGeneration) {
+ // We are locked to a ranged search in a single generation or we
are searching with the first
+ // portion of an overlapping range of entries in which case we
return the bucket that is the
+ // crossing point into the next generation.
+ if (boundToGeneration && bucket.generation != currentGeneration) {
return bucket;
}
+ currentGeneration = bucket.generation;
+
if (!foundFirst) {
if (bucket.isCapturedByRange(first, last)) {
final int result = bucket.search(first);
@@ -341,11 +397,9 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
if (ceiling < writeOffset) {
foundFirst = true;
readStart = ceiling;
- inGeneration = bucket.generation;
+ boundToGeneration = true;
}
- } else if (continuation && bucket.lowestDeliveryId > first) {
- // If continued from a range that include overflow and we
find values ahead of
- // the lowest point in this sequence we know there can be
no matches so stop now.
+ } else if (boundToGeneration &&
Integer.compareUnsigned(bucket.lowestDeliveryId, first) > 0) {
return null;
}
}
@@ -360,6 +414,10 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
if (comparison <= 0) {
action.accept(deliveries[j++]);
+
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException("Map was
modified during entry iteration");
+ }
}
foundLast = comparison >= 0;
@@ -381,6 +439,8 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
* The last entry to remove
* @param action
* The action to invoke on each remove.
+ *
+ * @throws ConcurrentModificationException if the {@link Map} is modified
by the provided action
*/
public void removeEach(int first, int last, Consumer<Delivery> action) {
Objects.requireNonNull(action);
@@ -397,18 +457,26 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
final UnsettledBucket<Delivery> nextGeneration =
removeEachInRange(tail, false, first,
UnsignedInteger.MAX_VALUE.intValue(), action);
+ // If the search found entries that matched the range then we can
continue at the
+ // generation boundary and try and match the range after the
overflow, If it did
+ // not match any range then we assume that the front half refers
to a range that
+ // has already been removed and we start from the oldest elements
again to try and
+ // satisfy the range portion after the overflow.
if (nextGeneration != null) {
removeEachInRange(nextGeneration, true, 0, last, action);
+ } else if (tail != null) {
+ removeEachInRange(tail, true, 0, last, action);
}
}
}
- private UnsettledBucket<Delivery>
removeEachInRange(UnsettledBucket<Delivery> tail, boolean continuation, int
first, int last, Consumer<Delivery> action) {
+ private UnsettledBucket<Delivery>
removeEachInRange(UnsettledBucket<Delivery> tail, boolean boundToGeneration,
int first, int last, Consumer<Delivery> action) {
boolean foundFirst = false;
boolean foundLast = false;
int removeStart = 0;
int removeEnd = 0;
- int inGeneration = continuation ? tail.generation : -1;
+ int currentGeneration = tail.generation;
+ int expectedModCount = modCount;
UnsettledBucket<Delivery> bucket = tail;
@@ -417,13 +485,15 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
removeStart = bucket.readOffset;
- // We are locked to a ranged search in a single generation so if
values
- // jump we can stop and return where the next generation starts in
case
- // the caller has a second range to check.
- if (inGeneration >= 0 && bucket.generation != inGeneration) {
+ // We are locked to a ranged search in a single generation or we
are searching with the first
+ // portion of an overlapping range of entries in which case we
return the bucket that is the
+ // crossing point into the next generation.
+ if (boundToGeneration && bucket.generation != currentGeneration) {
return bucket;
}
+ currentGeneration = bucket.generation;
+
if (!foundFirst) {
if (bucket.isCapturedByRange(first, last)) {
final int result = bucket.search(first);
@@ -437,11 +507,9 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
if (ceiling < writeOffset) {
foundFirst = true;
removeStart = ceiling;
- inGeneration = bucket.generation;
+ boundToGeneration = true;
}
- } else if (continuation && bucket.lowestDeliveryId > first) {
- // If continued from a range that include overflow and we
find values ahead of
- // the lowest point in this sequence we know there can be
no matches so stop now.
+ } else if (boundToGeneration &&
Integer.compareUnsigned(bucket.lowestDeliveryId, first) > 0) {
return null;
}
}
@@ -456,12 +524,17 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
if (comparison <= 0) {
action.accept(deliveries[removeEnd++]);
+
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException("Map was
modified during entry iteration");
+ }
}
foundLast = comparison >= 0;
}
bucket = removeRange(bucket, removeStart, removeEnd,
foundLast);
+ expectedModCount = modCount;
} else {
bucket = bucket.next;
}
@@ -478,6 +551,8 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
return;
}
+ final int expectedModCount = modCount;
+
for (UnsettledBucket<Delivery> bucket = tail; bucket != null; bucket =
bucket.next) {
final int writeOffset = bucket.writeOffset;
final Delivery[] deliveries = bucket.deliveries;
@@ -485,6 +560,10 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
for (int j = bucket.readOffset; j < writeOffset; ++j) {
action.accept(UnsignedInteger.valueOf(deliveryIds[j]),
deliveries[j]);
+
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException("Map was
modified during entry iteration");
+ }
}
}
}
@@ -492,7 +571,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public Collection<Delivery> values() {
if (values == null) {
- values = new UnsettledTackingMapValues();
+ values = new UnsettledTrackingMapValues();
}
return values;
@@ -501,7 +580,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public Set<UnsignedInteger> keySet() {
if (keySet == null) {
- keySet = new UnsettledTackingMapKeys();
+ keySet = new UnsettledTrackingMapKeys();
}
return this.keySet;
@@ -510,7 +589,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public Set<Entry<UnsignedInteger, Delivery>> entrySet() {
if (entrySet == null) {
- entrySet = new UnsettledTackingMapEntries();
+ entrySet = new UnsettledTrackingMapEntries();
}
return this.entrySet;
@@ -531,11 +610,22 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
try {
- for (UnsettledBucket<Delivery> bucket = tail; bucket != null;
bucket = bucket.next) {
- for (int j = bucket.readOffset; j < bucket.writeOffset; ++j) {
- final Delivery delivery = bucket.deliveries[j];
- if (!delivery.equals(m.get(bucket.deliveryIds[j]))) {
- return false;
+ if (m instanceof UnsettledMap um) {
+ for (UnsettledBucket<Delivery> bucket = tail; bucket != null;
bucket = bucket.next) {
+ for (int j = bucket.readOffset; j < bucket.writeOffset;
++j) {
+ final Delivery delivery = bucket.deliveries[j];
+ if (!delivery.equals(um.get(bucket.deliveryIds[j]))) {
+ return false;
+ }
+ }
+ }
+ } else {
+ for (UnsettledBucket<Delivery> bucket = tail; bucket != null;
bucket = bucket.next) {
+ for (int j = bucket.readOffset; j < bucket.writeOffset;
++j) {
+ final Delivery delivery = bucket.deliveries[j];
+ if
(!delivery.equals(m.get(UnsignedInteger.valueOf(bucket.deliveryIds[j])))) {
+ return false;
+ }
}
}
}
@@ -554,39 +644,50 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
//----- Internal UnsettledMap API
+ // Must be called only after checking that the map is not empty
private Delivery findDelivery(int deliveryId, boolean remove) {
- if (size == 0) {
- return null;
- }
-
final boolean hasNotOverflowed = generations == 0;
final int globalLow = tail.lowestDeliveryId;
final int globalHigh = head.highestDeliveryId;
if (hasNotOverflowed) {
- // When there is no overflow in the map we can fast path check for
the delivery
- // being outside the global range and exit early. All other cases
of overflow
- // requires some caution and we search all the buckets for a match.
- if (Integer.compareUnsigned(deliveryId, globalLow) < 0 ||
- Integer.compareUnsigned(deliveryId, globalHigh) > 0) {
- return null;
- }
+ return findWhenNoOverflow(deliveryId, remove, globalHigh,
globalLow);
+ } else {
+ return findWhenOverflow(deliveryId, remove);
+ }
+ }
+
+ private Delivery findWhenNoOverflow(int deliveryId, boolean remove, int
globalHigh, int globalLow) {
+ // When there is no overflow in the map we can fast path check for the
delivery
+ // being outside the global range and exit early. All other cases of
overflow
+ // requires some caution and we search all the buckets for a match.
+ if (Integer.compareUnsigned(deliveryId, globalLow) < 0 ||
+ Integer.compareUnsigned(deliveryId, globalHigh) > 0) {
+ return null;
}
final UnsettledBucket<Delivery> tail = this.tail;
+ final UnsettledBucket<Delivery> head = this.head;
+
+ // The delivery holding the highest tracked ID is always the last
entry written into the head
+ // bucket, and while no overflow is active the IDs form a unique
increasing series so no other
+ // bucket can hold it. Likewise the lowest delivery ID is always at
the read offset of the tail
+ // bucket so directly accessing it is safe.
+ if (deliveryId == globalHigh) {
+ return remove ? getAndRemove(head, head.writeOffset - 1) :
head.deliveries[head.writeOffset - 1];
+ } else if (deliveryId == globalLow) {
+ return remove ? getAndRemove(tail, tail.readOffset) :
tail.deliveries[tail.readOffset];
+ }
if (tail.isInRange(deliveryId)) {
final int deliveryIndex = tail.search(deliveryId);
+
if (deliveryIndex >= 0) {
return remove ? getAndRemove(tail, deliveryIndex) :
tail.deliveries[deliveryIndex];
}
}
- if (head == tail) {
- return null;
- }
-
- if (hasNotOverflowed) {
+ if (head != tail) {
final int distFromTail = deliveryId - globalLow;
final int distToHead = globalHigh - deliveryId;
@@ -594,10 +695,29 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
// by generations being greater than zero.
if (Integer.compareUnsigned(distFromTail, distToHead) > 0) {
return searchBackwards(deliveryId, head, remove);
+ } else {
+ return searchForwards(deliveryId, tail.next, remove, true);
}
}
- return searchForwards(deliveryId, tail.next, remove, hasNotOverflowed);
+ return null;
+ }
+
+ private Delivery findWhenOverflow(int deliveryId, boolean remove) {
+ final UnsettledBucket<Delivery> tail = this.tail;
+
+ if (tail.isInRange(deliveryId)) {
+ final int deliveryIndex = tail.search(deliveryId);
+ if (deliveryIndex >= 0) {
+ return remove ? getAndRemove(tail, deliveryIndex) :
tail.deliveries[deliveryIndex];
+ }
+ }
+
+ if (head != tail) {
+ return searchForwards(deliveryId, tail.next, remove, false);
+ }
+
+ return null;
}
private Delivery searchForwards(int deliveryId, UnsettledBucket<Delivery>
target, boolean remove, boolean canStopEarly) {
@@ -665,14 +785,18 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
private UnsettledBucket<Delivery> advanceHead() {
if (free == null) {
- for (int i = 0; i < FREE_LIST_GROWTH_AMOUNT; i++) {
+ // On first use match the initial buckets configuration otherwise
just create a
+ // new bucket to meet the current request
+ final int newBuckets = head == null ? initialBucketCount : 1;
+
+ for (int i = 0; i < newBuckets; i++) {
UnsettledBucket<Delivery> bucket = new
UnsettledBucket<Delivery>(bucketCapacity);
bucket.prev = free;
free = bucket;
}
- freeListSize = FREE_LIST_GROWTH_AMOUNT;
+ freeListSize = newBuckets;
}
// Pop a bucket off the free list
@@ -701,6 +825,10 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
final int removals = end - start;
final UnsettledBucket<Delivery> next = bucket.next;
+ if (removals == 0) {
+ return next;
+ }
+
this.size -= removals;
this.modCount++;
@@ -763,25 +891,28 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
}
- // Called from iteration APIs which requires the method to return the
location of the next
- // entry once removal and possible bucket compaction is completed.
- private IteratorRemoveResult<Delivery> removeAt(UnsettledBucket<Delivery>
bucket, int bucketEntry) {
+ // Called from the iteration APIs which requires the method to move the
given iterator to the
+ // location of the next entry once removal and possible bucket compaction
is completed. The next
+ // location is written directly into the iterator rather than returned in
a holder object as
+ // that avoids an allocation for every entry removed by an iterator.
+ private void removeAt(UnsettledTrackingMapIterator<?> iterator,
UnsettledBucket<Delivery> bucket, int bucketEntry) {
final int entriesRead = bucketEntry - bucket.readOffset; // compute
now before entries shift
bucketEntry = bucket.removeIndex(bucketEntry);
size--;
modCount++;
- IteratorRemoveResult<Delivery> result = null;
+ UnsettledBucket<Delivery> nextEntryBucket = null;
+ int nextEntryOffset = -1;
if (bucket.isReadable()) {
final UnsettledBucket<Delivery> next = bucket.next;
final UnsettledBucket<Delivery> prev = bucket.prev;
final UnsettledBucket<Delivery> nextBucket = (bucket == head ||
next == null) ||
- Integer.compareUnsigned(bucket.highestDeliveryId,
next.lowestDeliveryId) >= 0 ? ALWAYS_FULL_BUCKET : next;
+ Integer.compareUnsigned(bucket.highestDeliveryId,
next.lowestDeliveryId) >= 0 ? alwaysFullBucket() : next;
final UnsettledBucket<Delivery> prevBucket = (bucket == tail ||
prev == null) ||
- Integer.compareUnsigned(bucket.lowestDeliveryId,
prev.highestDeliveryId) <= 0 ? ALWAYS_FULL_BUCKET : prev;
+ Integer.compareUnsigned(bucket.lowestDeliveryId,
prev.highestDeliveryId) <= 0 ? alwaysFullBucket() : prev;
// As soon as compaction is possible move elements from this
bucket into previous and next
// which reduces search times as there are fewer buckets to
traverse/
@@ -794,9 +925,14 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
recycleBucket(bucket);
if (readOffset > 0) {
- result = new IteratorRemoveResult<Delivery>(prevBucket,
prevBucket.writeOffset - readOffset);
- } else {
- result = new IteratorRemoveResult<Delivery>(nextBucket,
nextBucket.readOffset - readOffset);
+ nextEntryBucket = prevBucket;
+ nextEntryOffset = prevBucket.writeOffset - readOffset;
+ } else if (nextBucket != ALWAYS_FULL_BUCKET) {
+ nextEntryBucket = nextBucket;
+ nextEntryOffset = nextBucket.readOffset - readOffset;
+ } else if (next != null) {
+ nextEntryBucket = next;
+ nextEntryOffset = next.readOffset - readOffset;
}
} else {
// If there is more to read in the current bucket we can just
choose the
@@ -805,9 +941,11 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
// tail bucket. We need to check though that the next bucket
is readable as it
// could be the head bucket but there could be nothing in
there.
if (bucketEntry < bucket.writeOffset) {
- result = new IteratorRemoveResult<Delivery>(bucket,
bucketEntry);
+ nextEntryBucket = bucket;
+ nextEntryOffset = bucketEntry;
} else if (bucket != head) {
- result = new IteratorRemoveResult<Delivery>(nextBucket,
nextBucket.readOffset);
+ nextEntryBucket = next;
+ nextEntryOffset = next.readOffset;
}
}
} else {
@@ -820,18 +958,23 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
recycleBucket(bucket);
if (next != null) {
- result = new IteratorRemoveResult<Delivery>(next,
next.readOffset);
+ nextEntryBucket = next;
+ nextEntryOffset = next.readOffset;
}
}
- return result;
+ if (nextEntryBucket != null && nextEntryBucket != alwaysFullBucket()) {
+ iterator.updatePosition(nextEntryBucket, nextEntryOffset);
+ } else {
+ iterator.markComplate();
+ }
}
// This method is called knowing that there is enough space either in
front of, or behind the target
// bucket to accommodate all its entries so there are no checks here to
validate that assumption.
// We do not clear or update the actual bucket state here but instead
allow the natural cleanup
// of the recycle method handle that for us.
- private final void doCompaction(UnsettledBucket<Delivery> bucket,
UnsettledBucket<Delivery> prev, UnsettledBucket<Delivery> next) {
+ private void doCompaction(UnsettledBucket<Delivery> bucket,
UnsettledBucket<Delivery> prev, UnsettledBucket<Delivery> next) {
final Object[] srcDeliveries = bucket.deliveries;
final int[] srcDeliveryIds = bucket.deliveryIds;
@@ -900,10 +1043,10 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
if (bucket.isReadable()) {
final UnsettledBucket<Delivery> nextBucket =
(next == null || bucket == head) ||
- Integer.compareUnsigned(bucket.highestDeliveryId,
next.lowestDeliveryId) >= 0 ? ALWAYS_FULL_BUCKET : next;
+ Integer.compareUnsigned(bucket.highestDeliveryId,
next.lowestDeliveryId) >= 0 ? alwaysFullBucket() : next;
final UnsettledBucket<Delivery> prevBucket =
(prev == null || bucket == tail) ||
- Integer.compareUnsigned(bucket.lowestDeliveryId,
prev.highestDeliveryId) <= 0 ? ALWAYS_FULL_BUCKET : prev;
+ Integer.compareUnsigned(bucket.lowestDeliveryId,
prev.highestDeliveryId) <= 0 ? alwaysFullBucket() : prev;
// As soon as compaction is possible move elements from this
bucket into previous and next
// which reduces search times as there are fewer buckets to
traverse/
@@ -916,6 +1059,11 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
}
+ @SuppressWarnings("unchecked")
+ private static <Delivery> UnsettledBucket<Delivery> alwaysFullBucket() {
+ return ALWAYS_FULL_BUCKET;
+ }
+
//----- Internal bucket of delivery sequence
@SuppressWarnings("unchecked")
@@ -1067,10 +1215,13 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
lowestDeliveryId = UnsignedInteger.MAX_VALUE.intValue();
highestDeliveryId = writeOffset = readOffset = entries = 0;
next = prev = null;
+ generation = 0;
}
@Override
public String toString() {
+ // We will not render the full Map unlike other Map types because
that
+ // could be a large performance hit in logging in the engine.
return "UnsettledBucket { size=" + entries +
" roff=" + readOffset +
" woff=" + writeOffset +
@@ -1091,7 +1242,9 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
* a negative value e.g. -(index - 1).
*/
public int search(int deliveryId) {
- if (deliveryIds[readOffset] == deliveryId) {
+ if (entries == 0) {
+ return ~readOffset;
+ } else if (deliveryIds[readOffset] == deliveryId) {
return readOffset;
} else if (entries < BINARY_SEARCH_THRESHOLD) {
return linearSearch(deliveryId, readOffset, writeOffset);
@@ -1167,13 +1320,13 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
// do not have state the trivial race on create is not important to the
eventual
// outcome of having a cached instance.
- protected Set<UnsignedInteger> keySet;
- protected Collection<Delivery> values;
- protected Set<Entry<UnsignedInteger, Delivery>> entrySet;
+ private Set<UnsignedInteger> keySet;
+ private Collection<Delivery> values;
+ private Set<Entry<UnsignedInteger, Delivery>> entrySet;
//----- Unsettled Tracking Map Collection types
- private final class UnsettledTackingMapValues extends
AbstractCollection<Delivery> {
+ private final class UnsettledTrackingMapValues extends
AbstractCollection<Delivery> {
@Override
public Iterator<Delivery> iterator() {
@@ -1192,10 +1345,18 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public boolean remove(Object target) {
- @SuppressWarnings("unchecked")
- final int targetId =
UnsettledMap.this.deliveryIdSupplier.getDeliveryId((Delivery) target);
+ if (target == null) {
+ return false;
+ }
+
+ try {
+ @SuppressWarnings("unchecked")
+ final int targetId =
UnsettledMap.this.deliveryIdSupplier.getDeliveryId((Delivery) target);
- return UnsettledMap.this.remove(targetId) != null;
+ return UnsettledMap.this.remove(targetId) != null;
+ } catch (ClassCastException ccex) {
+ return false;
+ }
}
@Override
@@ -1204,7 +1365,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
}
- private final class UnsettledTackingMapKeys extends
AbstractSet<UnsignedInteger> {
+ private final class UnsettledTrackingMapKeys extends
AbstractSet<UnsignedInteger> {
@Override
public Iterator<UnsignedInteger> iterator() {
@@ -1224,7 +1385,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
public boolean remove(Object target) {
if (target instanceof Number number) {
- return UnsettledMap.this.remove(number.intValue()) != null;
+ return UnsettledMap.this.remove(number) != null;
}
return false;
}
@@ -1235,7 +1396,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
}
}
- private final class UnsettledTackingMapEntries extends
AbstractSet<Map.Entry<UnsignedInteger, Delivery>> {
+ private final class UnsettledTrackingMapEntries extends
AbstractSet<Map.Entry<UnsignedInteger, Delivery>> {
@Override
public Iterator<Map.Entry<UnsignedInteger, Delivery>> iterator() {
@@ -1253,7 +1414,11 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@SuppressWarnings("unchecked")
final Entry<? extends UnsignedInteger, ? extends Delivery>
entry =
(Entry<? extends UnsignedInteger, ? extends Delivery>)
target;
- return UnsettledMap.this.containsKey(entry.getKey());
+ final Delivery delivery =
UnsettledMap.this.get(entry.getKey());
+
+ if (delivery != null) {
+ return delivery.equals(entry.getValue());
+ }
}
return false;
@@ -1279,10 +1444,6 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
//----- Map Iterator implementation for EntrySet, KeySet and Values
collections
- private record IteratorRemoveResult<Delivery>(UnsettledBucket<Delivery>
bucket, int readOffset) {
-
- }
-
// Base class iterator that can be used for the collections returned from
the Map
private abstract class UnsettledTrackingMapIterator<T> implements
Iterator<T> {
@@ -1312,7 +1473,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
throw new NoSuchElementException();
}
if (expectedModCount != UnsettledMap.this.modCount) {
- throw new ConcurrentModificationException();
+ throw new ConcurrentModificationException("Map was modified
during entry iteration");
}
lastReturnedBucket = currentBucket;
@@ -1331,23 +1492,25 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
throw new IllegalStateException("Cannot remove entry when next
has not been called");
}
if (modCount != expectedModCount) {
- throw new ConcurrentModificationException();
+ throw new ConcurrentModificationException("Map was modified
during entry iteration");
}
- final IteratorRemoveResult<Delivery> result =
UnsettledMap.this.removeAt(lastReturnedBucket, lastReturnedBucketIndex);
-
- if (result != null) {
- currentBucket = result.bucket;
- readOffset = result.readOffset;
- } else {
- currentBucket = null;
- readOffset = -1;
- }
+ UnsettledMap.this.removeAt(this, lastReturnedBucket,
lastReturnedBucketIndex);
expectedModCount = modCount;
lastReturned = null;
}
+ protected void updatePosition(UnsettledBucket<Delivery> bucket, int
bucketEntry) {
+ this.currentBucket = bucket;
+ this.readOffset = bucketEntry;
+ }
+
+ protected void markComplate() {
+ this.currentBucket = null;
+ this.readOffset = -1;
+ }
+
private void successor() {
if (++readOffset == currentBucket.writeOffset) {
currentBucket = currentBucket.next;
@@ -1392,7 +1555,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
@Override
protected Entry<UnsignedInteger, Delivery>
entryAt(UnsettledBucket<Delivery> bucket, int bucketEntry) {
- return new ImmutableUnsettledTrackingkMapEntry<Delivery>(
+ return new ImmutableUnsettledTrackingMapEntry<Delivery>(
bucket.deliveryIds[bucketEntry],
bucket.deliveries[bucketEntry]);
}
}
@@ -1403,7 +1566,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
*
* @param <Delivery> Type of the value portion of this immutable entry.
*/
- public static class ImmutableUnsettledTrackingkMapEntry<Delivery>
implements Map.Entry<UnsignedInteger, Delivery> {
+ public static class ImmutableUnsettledTrackingMapEntry<Delivery>
implements Map.Entry<UnsignedInteger, Delivery> {
private final int key;
private final Delivery value;
@@ -1416,7 +1579,7 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
* @param value
* The inner {@link Map} value that is wrapped.
*/
- public ImmutableUnsettledTrackingkMapEntry(int key, Delivery value) {
+ public ImmutableUnsettledTrackingMapEntry(int key, Delivery value) {
this.key = key;
this.value = value;
}
@@ -1442,5 +1605,26 @@ public class UnsettledMap<Delivery> implements
Map<UnsignedInteger, Delivery> {
public Delivery setValue(Delivery value) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public int hashCode() {
+ return key ^ value.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ if (obj instanceof ImmutableUnsettledTrackingMapEntry other) {
+ return key == other.key && Objects.equals(value, other.value);
+ } else if (obj instanceof Map.Entry<?, ?> entry) {
+ return UnsignedInteger.valueOf(key).equals(entry.getKey()) &&
+ Objects.equals(value, entry.getValue());
+ }
+
+ return false;
+ }
}
-}
\ No newline at end of file
+}
diff --git
a/protonj2/src/test/java/org/apache/qpid/protonj2/engine/util/UnsettledMapTest.java
b/protonj2/src/test/java/org/apache/qpid/protonj2/engine/util/UnsettledMapTest.java
index 034df0fd..eb1c1cd8 100644
---
a/protonj2/src/test/java/org/apache/qpid/protonj2/engine/util/UnsettledMapTest.java
+++
b/protonj2/src/test/java/org/apache/qpid/protonj2/engine/util/UnsettledMapTest.java
@@ -17,6 +17,7 @@
package org.apache.qpid.protonj2.engine.util;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -57,7 +58,7 @@ import org.junit.jupiter.api.Test;
*/
public class UnsettledMapTest {
- protected static final ProtonLogger LOG =
ProtonLoggerFactory.getLogger(SplayMapTest.class);
+ protected static final ProtonLogger LOG =
ProtonLoggerFactory.getLogger(UnsettledMapTest.class);
protected long seed;
protected Random random;
@@ -88,10 +89,31 @@ public class UnsettledMapTest {
return new UnsettledMap<>(DeliveryType::getDeliveryId, numBuckets,
bucketSize);
}
+ /**
+ * Asserts that each delivery the tracker still counts as unsettled can be
found by its ID. A
+ * delivery that survives in the tracker but cannot be located by a random
access search could
+ * never be settled by a disposition again.
+ * <p>
+ * The check visits every tracked delivery and searches for it by ID,
which costs more than the
+ * operations it guards, so the random tests only run it at intervals and
once at the end.
+ */
+ private void
assertAllTrackedDeliveriesAreReachable(UnsettledMap<DeliveryType> tracker) {
+ int visited = 0;
+
+ for (DeliveryType delivery : tracker.values()) {
+ final int deliveryId = delivery.getDeliveryId();
+ assertNotNull(tracker.get(deliveryId),
+ "Delivery " + UnsignedInteger.valueOf(deliveryId) + " should
be reachable by its ID");
+ visited++;
+ }
+
+ assertEquals(tracker.size(), visited, "The values view should visit
each tracked delivery once");
+ }
+
/**
* Simple delivery type used for this test
*/
- private class DeliveryType {
+ private static class DeliveryType {
private final int deliveryId;
@@ -144,6 +166,16 @@ public class UnsettledMapTest {
assertNotNull(tracker.toString());
}
+ @SuppressWarnings("unlikely-arg-type")
+ @Test
+ public void testMapRejectedOversizedLongObjects() {
+ UnsettledMap<DeliveryType> tracker = createMap();
+
+ assertNull(tracker.get(Long.valueOf(Long.MAX_VALUE)));
+ assertNull(tracker.remove(Long.valueOf(Long.MAX_VALUE)));
+ assertFalse(tracker.containsKey(Long.valueOf(Long.MAX_VALUE)));
+ }
+
@Test
public void testCreateUnsettledTracker() {
UnsettledMap<DeliveryType> tracker = createMap();
@@ -176,6 +208,14 @@ public class UnsettledMapTest {
assertNull(tracker.get("foo"));
}
+ @Test
+ public void testValuesRemoveNullReturnsFalsePerCollectionsContract() {
+ final UnsettledMap<DeliveryType> map = createMap();
+ map.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+
+ assertFalse(map.values().remove(null));
+ }
+
@Test
public void testGet() {
UnsettledMap<DeliveryType> tracker = createMap();
@@ -1146,7 +1186,7 @@ public class UnsettledMapTest {
}
@Test
- public void
TestKeySetRetainAllFromCollectionWhenMapHasCustomBucketsAndRetainedIsInFirstBucket()
{
+ public void
testKeySetRetainAllFromCollectionWhenMapHasCustomBucketsAndRetainedIsInFirstBucket()
{
// Start with three buckets of size three
UnsettledMap<DeliveryType> tracker = createMap(3, 3);
@@ -1211,7 +1251,7 @@ public class UnsettledMapTest {
@SuppressWarnings("unlikely-arg-type")
@Test
- public void tesEntrySetReturned() {
+ public void testEntrySetReturned() {
UnsettledMap<DeliveryType> tracker = createMap();
tracker.put(0, new DeliveryType(0));
@@ -1225,8 +1265,8 @@ public class UnsettledMapTest {
assertFalse(entries.isEmpty());
assertSame(entries, tracker.entrySet());
- final UnsettledMap.ImmutableUnsettledTrackingkMapEntry<DeliveryType>
entry =
- new
UnsettledMap.ImmutableUnsettledTrackingkMapEntry<DeliveryType>(3, new
DeliveryType(3));
+ final UnsettledMap.ImmutableUnsettledTrackingMapEntry<DeliveryType>
entry =
+ new
UnsettledMap.ImmutableUnsettledTrackingMapEntry<DeliveryType>(3, new
DeliveryType(3));
assertEquals(3, entry.getPrimitiveKey());
assertEquals(3, entry.getValue().getDeliveryId());
@@ -1245,7 +1285,7 @@ public class UnsettledMapTest {
}
@Test
- public void tesEntrySetContains() {
+ public void testEntrySetContainsSimple() {
UnsettledMap<DeliveryType> tracker = createMap();
tracker.put(0, new DeliveryType(0));
@@ -1324,7 +1364,7 @@ public class UnsettledMapTest {
}
@Test
- public void testEntryIterationFollowsInterstionOrderingExpectations() {
+ public void testEntryIterationFollowsIntersectionOrderingExpectations() {
UnsettledMap<DeliveryType> tracker = createMap();
final int[] inputValues = {3, 0, -1, 1, -2, 2};
@@ -1399,13 +1439,21 @@ public class UnsettledMapTest {
tracker.put(UnsignedInteger.valueOf(i), new DeliveryType(i));
}
+ assertAllTrackedDeliveriesAreReachable(tracker);
+
for (int i = 0; i < ITERATIONS; ++i) {
int p = random.nextInt(ITERATIONS);
int c = random.nextInt(ITERATIONS);
tracker.put(UnsignedInteger.valueOf(p), new DeliveryType(p));
tracker.remove(UnsignedInteger.valueOf(c));
+
+ if (i % 2048 == 0) {
+ assertAllTrackedDeliveriesAreReachable(tracker);
+ }
}
+
+ assertAllTrackedDeliveriesAreReachable(tracker);
} catch (Throwable error) {
dumpRandomDataSet(ITERATIONS, seed, true);
throw error;
@@ -1425,7 +1473,13 @@ public class UnsettledMapTest {
tracker.put(UnsignedInteger.valueOf(p), new DeliveryType(p));
tracker.remove(UnsignedInteger.valueOf(c));
+
+ if (i % 2048 == 0) {
+ assertAllTrackedDeliveriesAreReachable(tracker);
+ }
}
+
+ assertAllTrackedDeliveriesAreReachable(tracker);
} catch (Throwable error) {
dumpRandomDataSet(ITERATIONS, seed, true);
throw error;
@@ -1445,7 +1499,13 @@ public class UnsettledMapTest {
tracker.put(UnsignedInteger.valueOf(p), new DeliveryType(p));
tracker.remove(UnsignedInteger.valueOf(c));
+
+ if (i % 2048 == 0) {
+ assertAllTrackedDeliveriesAreReachable(tracker);
+ }
}
+
+ assertAllTrackedDeliveriesAreReachable(tracker);
} catch (Throwable error) {
dumpRandomDataSet(ITERATIONS, seed, true);
throw error;
@@ -1997,6 +2057,30 @@ public class UnsettledMapTest {
assertTrue(tracker.containsKey(1));
}
+ @Test
+ public void testHighestIdLookupFindsEarliestInstanceOfADuplicateId() {
+ UnsettledMap<DeliveryType> tracker = createMap();
+
+ DeliveryType original = new DeliveryType(1);
+ DeliveryType duplicate = new DeliveryType(1);
+
+ tracker.put(1, original);
+ tracker.put(1, duplicate); // duplicate ID forces a new generation at
the head
+
+ // The ID being sought is the highest of the series and so the head
bucket case, however the
+ // search from the tail must still win while an overflow is active as
that is where the
+ // matching series starts.
+ assertSame(original, tracker.get(1), "Should have found the original
instance of the ID");
+ assertSame(original, tracker.remove(1), "Should have removed the
original instance of the ID");
+
+ // The remaining instance is now the only match for the ID and also
the highest of the
+ // series, which is the case answered directly from the head bucket.
+ assertSame(duplicate, tracker.get(1), "Should have found the remaining
instance of the ID");
+ assertSame(duplicate, tracker.remove(1), "Should have removed the
remaining instance of the ID");
+
+ assertTrue(tracker.isEmpty(), "All tracked deliveries should have been
settled");
+ }
+
@Test
public void testIteratorRemoveAllSequentially() {
UnsettledMap<DeliveryType> tracker = createMap();
@@ -2161,13 +2245,7 @@ public class UnsettledMapTest {
removed = it.next();
}
- try {
- it.remove();
- } catch (IndexOutOfBoundsException ex) {
- fail("Iterator remove threw IndexOutOfBoundsException for
bucketSize=" + bucketSize +
- " at index > 256 which is beyond the default bucket capacity
value. ");
- }
-
+ assertDoesNotThrow(() -> it.remove());
assertNotNull(removed);
assertNull(tracker.get(removed.getDeliveryId()));
assertEquals(bucketSize - 1, tracker.size());
@@ -2962,6 +3040,60 @@ public class UnsettledMapTest {
assertTrue(visited.contains(-1));
}
+ @Test
+ public void testForEachAndRemoveEachCoverOneSeriesOfDeliveriesAtATime() {
+ final UnsettledMap<DeliveryType> map = createMap(4, 8);
+
+ // Deliveries of a first series of IDs, the next two IDs roll the
series backwards which
+ // begins a second series of deliveries that is tracked alongside the
first one.
+ map.put(100, new DeliveryType(100));
+ map.put(101, new DeliveryType(101));
+ map.put(102, new DeliveryType(102));
+ map.put(50, new DeliveryType(50));
+ map.put(51, new DeliveryType(51));
+
+ assertEquals(5, map.size(), "Every delivery added should be tracked");
+ assertAllTrackedDeliveriesAreReachable(map);
+
+ final List<Integer> visited = new ArrayList<>();
+ map.forEach(50, 200, (delivery) ->
visited.add(delivery.getDeliveryId()));
+
+ // A ranged visit covers a single series of deliveries at a time so
only the oldest series
+ // is visited even though the range also holds the deliveries of the
newer series.
+ assertEquals(Arrays.asList(100, 101, 102), visited,
+ "The ranged visit should cover the deliveries of the first series:
" + visited);
+ assertEquals(5, map.size(), "forEach should not alter the tracker
contents");
+ assertAllTrackedDeliveriesAreReachable(map);
+
+ // A range that only holds the deliveries of the newer series covers
them regardless of the
+ // series that precedes them in the tracker.
+ final List<Integer> newerSeries = new ArrayList<>();
+ map.forEach(50, 60, (delivery) ->
newerSeries.add(delivery.getDeliveryId()));
+
+ assertEquals(Arrays.asList(50, 51), newerSeries,
+ "The range of the newer series should cover its deliveries: " +
newerSeries);
+ assertEquals(5, map.size(), "forEach should not alter the tracker
contents");
+
+ final List<Integer> removed = new ArrayList<>();
+ map.removeEach(50, 200, (delivery) ->
removed.add(delivery.getDeliveryId()));
+
+ assertEquals(Arrays.asList(100, 101, 102), removed,
+ "The ranged removal should cover the same deliveries as the ranged
visit: " + removed);
+ assertEquals(2, map.size(), "Only the deliveries of the covered series
should have been removed");
+ assertNull(map.get(100), "Delivery within the range should have been
removed");
+ assertNotNull(map.get(50), "Delivery of the other series should still
be tracked");
+ assertAllTrackedDeliveriesAreReachable(map);
+
+ // The newer series remains tracked and is covered by the next pass
over the same range.
+ final List<Integer> continued = new ArrayList<>();
+ map.forEach(50, 200, (delivery) ->
continued.add(delivery.getDeliveryId()));
+
+ assertEquals(Arrays.asList(50, 51), continued,
+ "The next pass over the range should cover the remaining series: "
+ continued);
+ assertEquals(2, map.size(), "forEach should not alter the tracker
contents");
+ assertAllTrackedDeliveriesAreReachable(map);
+ }
+
//----- removeEach method test variations
@Test
@@ -3540,4 +3672,736 @@ public class UnsettledMapTest {
// Should stop at end of Gen 0 and not bleed into Gen 1
assertEquals(2, count.get());
}
+
+ @Test
+ public void testIteratorRemoveEveryOtherEntryFromExactlyFilledBuckets() {
+ final UnsettledMap<DeliveryType> map = createMap(2, 2); // Two buckets
of two entries
+
+ for (int i = 0; i < 4; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ // The head bucket is exactly full and the removed entry is the last
entry of that
+ // bucket, which forces the remaining entries to be compacted into the
previous bucket.
+ final Iterator<DeliveryType> iterator = map.values().iterator();
+ int visited = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ visited++;
+ if (visited % 2 == 0) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(4, visited, "Iteration should visit all four entries");
+ assertEquals(2, map.size(), "Half of the deliveries should have been
removed");
+ assertNotNull(map.get(0), "Even numbered deliveries should still be
tracked");
+ assertNull(map.get(1), "Odd numbered deliveries should have been
removed");
+ assertNotNull(map.get(2), "Even numbered deliveries should still be
tracked");
+ assertNull(map.get(3), "Odd numbered deliveries should have been
removed");
+ }
+
+ @Test
+ public void testIteratorRemoveEveryOtherEntryFromDefaultSizedMap() {
+ final UnsettledMap<DeliveryType> map = createMap(); // Default bucket
size of 256
+
+ // Two buckets that are both exactly full when the iteration begins.
+ for (int i = 0; i < 512; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ final Iterator<DeliveryType> iterator = map.values().iterator();
+ int visited = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ visited++;
+ if (visited % 2 == 0) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(512, visited, "Iteration should visit all of the added
deliveries");
+ assertEquals(256, map.size(), "Half of the deliveries should have been
removed");
+
+ for (int i = 0; i < 512; i++) {
+ if (i % 2 == 0) {
+ assertNotNull(map.get(i), "Even delivery " + i + " should
still be tracked");
+ } else {
+ assertNull(map.get(i), "Odd delivery " + i + " should have
been removed");
+ }
+ }
+ }
+
+ @Test
+ public void testKeySetIteratorRemoveEveryOtherEntryFromDefaultSizedMap() {
+ final UnsettledMap<DeliveryType> map = createMap(); // Default bucket
size of 256
+
+ for (int i = 0; i < 512; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ final Iterator<UnsignedInteger> iterator = map.keySet().iterator();
+ int visited = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ visited++;
+ if (visited % 2 == 0) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(512, visited, "Iteration should visit all of the added
keys");
+ assertEquals(256, map.size(), "Half of the deliveries should have been
removed");
+ }
+
+ @Test
+ public void testEntrySetIteratorRemoveEveryOtherEntryFromDefaultSizedMap()
{
+ final UnsettledMap<DeliveryType> map = createMap(); // Default bucket
size of 256
+
+ for (int i = 0; i < 512; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ final Iterator<Entry<UnsignedInteger, DeliveryType>> iterator =
map.entrySet().iterator();
+ int visited = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ visited++;
+ if (visited % 2 == 0) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(512, visited, "Iteration should visit all of the added
entries");
+ assertEquals(256, map.size(), "Half of the deliveries should have been
removed");
+ }
+
+ @Test
+ public void
testRangedForEachWhenWrappedRangeStartsAtTheHighestPreWrapDeliveryId() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 50);
+
+ final int PRE_WRAP_LAST_DELIVERY_ID =
UnsignedInteger.MAX_VALUE.intValue() - 15;
+ final int PRE_WRAP_FIRST_DELIVERY_ID = PRE_WRAP_LAST_DELIVERY_ID - 4;
+
+ // Same contents as the tests above, built here so the two generation
layout is visible.
+ for (int i = PRE_WRAP_FIRST_DELIVERY_ID; i <=
PRE_WRAP_LAST_DELIVERY_ID; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+ for (int i = 0; i < 11; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ assertNotNull(map.get(PRE_WRAP_LAST_DELIVERY_ID), "Delivery before the
overflow should be tracked");
+ assertNotNull(map.get(10), "Delivery following the overflow should be
tracked");
+
+ // Counterpart of the first test above: when the start of the range is
covered by the
+ // deliveries that preceded the overflow, the visit does continue into
the deliveries that
+ // follow the overflow.
+ final List<Integer> visited = new ArrayList<>();
+ map.forEach(PRE_WRAP_LAST_DELIVERY_ID, 5, (delivery) ->
visited.add(delivery.getDeliveryId()));
+
+ assertEquals(7, visited.size(), "Ranged visit should cover both sides
of the overflow: " + visited);
+ assertTrue(visited.contains(PRE_WRAP_LAST_DELIVERY_ID),
+ "The delivery that the range starts at should be visited: " +
visited);
+ for (int i = 0; i <= 5; i++) {
+ assertTrue(visited.contains(i), "Delivery " + i + " is within the
range and should be visited: " + visited);
+ }
+ assertEquals(16, map.size(), "forEach should not alter the tracker
contents");
+ }
+
+ @Test
+ public void testEqualsWithHashMapKeyedOnUnsignedInteger() {
+ final UnsettledMap<DeliveryType> unsettled = createMap();
+ final Map<UnsignedInteger, DeliveryType> hashMap = new HashMap<>();
+
+ for (int i = 1; i <= 5; i++) {
+ unsettled.put(i, new DeliveryType(i));
+ hashMap.put(UnsignedInteger.valueOf(i), new DeliveryType(i));
+ }
+
+ assertEquals(hashMap.size(), unsettled.size(), "Maps should hold the
same number of entries");
+ assertTrue(unsettled.equals(hashMap), "UnsettledMap should equal a
HashMap holding the same mappings");
+ assertTrue(hashMap.equals(unsettled), "Map equality should be
symmetric for a HashMap");
+ }
+
+ @Test
+ public void testEqualsWithTreeMapKeyedOnUnsignedInteger() {
+ final UnsettledMap<DeliveryType> unsettled = createMap();
+ final Map<UnsignedInteger, DeliveryType> treeMap = new TreeMap<>();
+
+ for (int i = 1; i <= 5; i++) {
+ unsettled.put(i, new DeliveryType(i));
+ treeMap.put(UnsignedInteger.valueOf(i), new DeliveryType(i));
+ }
+
+ assertEquals(treeMap.size(), unsettled.size(), "Maps should hold the
same number of entries");
+ assertTrue(unsettled.equals(treeMap), "UnsettledMap should equal a
TreeMap holding the same mappings");
+ assertTrue(treeMap.equals(unsettled), "Map equality should be
symmetric for a TreeMap");
+ }
+
+ @Test
+ public void testImmutableMapEntryEquals() {
+ final UnsettledMap<DeliveryType> first = createMap();
+ final UnsettledMap<DeliveryType> second = createMap();
+
+ first.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+ second.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+
+ final Entry<UnsignedInteger, DeliveryType> firstEntry =
first.entrySet().iterator().next();
+ final Entry<UnsignedInteger, DeliveryType> secondEntry =
second.entrySet().iterator().next();
+
+ assertEquals(firstEntry.getKey(), secondEntry.getKey(), "Entries
should hold the same key");
+ assertEquals(firstEntry.getValue(), secondEntry.getValue(), "Entries
should hold the same value");
+
+ assertTrue(firstEntry.equals(secondEntry),
+ "Map.Entry requires value based equality, the same mapping must
compare equal");
+ assertTrue(secondEntry.equals(firstEntry),
+ "Map.Entry equality must be symmetric for two equal mappings");
+ assertFalse(firstEntry.equals(Map.entry(UnsignedInteger.valueOf(1),
new DeliveryType(2))),
+ "Map.Entry instances with different values must not compare
equal");
+ }
+
+ @Test
+ public void testImmutableMapEntryHashCode() {
+ final UnsettledMap<DeliveryType> first = createMap();
+ final UnsettledMap<DeliveryType> second = createMap();
+
+ first.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+ second.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+
+ final Entry<UnsignedInteger, DeliveryType> firstEntry =
first.entrySet().iterator().next();
+ final Entry<UnsignedInteger, DeliveryType> secondEntry =
second.entrySet().iterator().next();
+
+ assertEquals(firstEntry.hashCode(), secondEntry.hashCode(),
+ "Equal Map.Entry instances must have the same hash code");
+ assertEquals(firstEntry.hashCode(),
+ Map.entry(UnsignedInteger.valueOf(1), new
DeliveryType(1)).hashCode(),
+ "Map.Entry hash codes must be based on the key and value, not the
instance identity");
+ }
+
+ @Test
+ public void testEntrySetContainsMatchesKeyAndValue() {
+ final UnsettledMap<DeliveryType> map = createMap();
+ map.put(UnsignedInteger.valueOf(1), new DeliveryType(1));
+
+
assertTrue(map.entrySet().contains(Map.entry(UnsignedInteger.valueOf(1), new
DeliveryType(1))),
+ "entrySet should contain an entry with the same key and value");
+
assertFalse(map.entrySet().contains(Map.entry(UnsignedInteger.valueOf(1), new
DeliveryType(2))),
+ "entrySet should not contain an entry that has the same key but a
different value");
+ }
+
+ @Test
+ public void testForEachDeliveryFailsWhenEntryRemovedByAction() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ // The visited delivery is a stand in for any action that settles
another delivery while
+ // the tracker is being traversed, which restructures the buckets
underneath the traversal.
+ assertThrows(ConcurrentModificationException.class, () ->
map.forEach(delivery -> {
+ if (delivery != null && delivery.getDeliveryId() == 5) {
+ map.remove(6);
+ }
+ }), "Removing from the tracker while forEach visits it should fail
fast as the iterators do");
+ }
+
+ @Test
+ public void testForEachEntryFailsWhenEntryRemovedByAction() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ assertThrows(ConcurrentModificationException.class, () ->
map.forEach((deliveryId, delivery) -> {
+ if (deliveryId.intValue() == 5) {
+ map.remove(6);
+ }
+ }), "Removing from the tracker while forEach visits it should fail
fast as the iterators do");
+ }
+
+ @Test
+ public void testRangedForEachFailsWhenEntryRemovedByAction() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ assertThrows(ConcurrentModificationException.class, () ->
map.forEach(0, 24, delivery -> {
+ if (delivery != null && delivery.getDeliveryId() == 5) {
+ map.remove(6);
+ }
+ }), "Removing from the tracker while a ranged forEach visits it should
fail fast as the iterators do");
+ }
+
+ @Test
+ public void testRemoveEachFailsWhenEntryRemovedByAction() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ // The ranged removal compacts the buckets once the action has run for
the entries it
+ // covers, so a removal by the action itself leaves that compaction
working on stale state.
+ assertThrows(ConcurrentModificationException.class, () ->
map.removeEach(0, 24, delivery -> {
+ if (delivery != null && delivery.getDeliveryId() == 5) {
+ map.remove(6);
+ }
+ }), "Removing from the tracker while removeEach visits it should fail
fast as the iterators do");
+ }
+
+ @Test
+ public void testForEachDeliveryFailsWhenEntryAddedByAction() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ final AtomicBoolean added = new AtomicBoolean();
+
+ // Only one delivery is added so that the traversal cannot run away
when no error is raised.
+ assertThrows(ConcurrentModificationException.class, () ->
map.forEach(delivery -> {
+ if (added.compareAndSet(false, true)) {
+ map.put(1000, new DeliveryType(1000));
+ }
+ }), "Adding to the tracker while forEach visits it should fail fast as
the iterators do");
+ }
+
+ @Test
+ public void testForEachActionsThatOnlyReadTheMapAreNotRejected() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 10);
+
+ for (int i = 0; i < 25; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ final AtomicInteger visited = new AtomicInteger();
+ map.forEach(delivery -> {
+ assertNotNull(delivery);
+ assertNotNull(map.get(delivery.getDeliveryId()), "Delivery should
still be tracked while visited");
+ assertTrue(map.containsKey(delivery.getDeliveryId()), "Delivery
should still be tracked while visited");
+ visited.incrementAndGet();
+ });
+
+ assertEquals(25, visited.get(), "An action that only reads the tracker
should visit every delivery");
+
+ final AtomicInteger rangedVisited = new AtomicInteger();
+ map.forEach(0, 24, delivery -> rangedVisited.incrementAndGet());
+
+ assertEquals(25, rangedVisited.get(), "An action that only reads the
tracker should visit every delivery");
+ assertEquals(25, map.size(), "An action that only reads the tracker
must not alter its contents");
+ }
+
+ @Test
+ public void
testRangedAccessAfterRemovalsCompactEntriesIntoAdjacentBuckets() {
+ final UnsettledMap<DeliveryType> map = createMap(3, 10);
+
+ for (int i = 0; i < 30; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+
+ // Removing a run that spans two buckets leaves those buckets
partially empty which lets the
+ // remaining entries be merged into the neighboring buckets. The
lowest and highest delivery
+ // IDs held by each bucket are re-derived as part of that work, and
every search either skips
+ // an entire bucket or stops searching the buckets entirely based on
those two values, so the
+ // merged buckets must still describe the entries they now hold.
+ final List<Integer> removed = new ArrayList<>();
+ map.removeEach(4, 15, (delivery) ->
removed.add(delivery.getDeliveryId()));
+
+ assertEquals(12, removed.size(), "Every delivery of the range should
have been removed: " + removed);
+ for (int i = 4; i <= 15; i++) {
+ assertTrue(removed.contains(i), "Delivery " + i + " is within the
range and should have been removed");
+ }
+ assertEquals(18, map.size(), "Only the deliveries covered by the range
should have been removed");
+
+ for (int i = 0; i < 30; i++) {
+ if (i >= 4 && i <= 15) {
+ assertNull(map.get(i), "Delivery " + i + " was within the
range and should not be tracked");
+ assertFalse(map.containsKey(i), "Delivery " + i + " was within
the range and should not be tracked");
+ } else {
+ assertNotNull(map.get(i), "Delivery " + i + " should still be
tracked after the entries were merged");
+ assertTrue(map.containsKey(i), "Delivery " + i + " should
still be tracked after the entries were merged");
+ }
+ }
+
+ // A range that covers both the entries that stayed put and the
entries that were moved must
+ // visit each one exactly once, and a range of only settled deliveries
must match nothing.
+ final List<Integer> visited = new ArrayList<>();
+ map.forEach(0, 29, (delivery) ->
visited.add(delivery.getDeliveryId()));
+
+ assertEquals(18, visited.size(), "Ranged visit should cover every
tracked delivery: " + visited);
+ for (int i = 0; i < 30; i++) {
+ if (i >= 4 && i <= 15) {
+ assertFalse(visited.contains(i), "Delivery " + i + " is no
longer tracked: " + visited);
+ } else {
+ assertTrue(visited.contains(i), "Delivery " + i + " is within
the range and should be visited: " + visited);
+ }
+ }
+
+ final List<Integer> settledRange = new ArrayList<>();
+ map.forEach(5, 15, (delivery) ->
settledRange.add(delivery.getDeliveryId()));
+
+ assertTrue(settledRange.isEmpty(), "No delivery of the settled range
should be visited: " + settledRange);
+
+ // Removing the entries that were moved into the first bucket pulls
the highest delivery ID
+ // tracked by that bucket back again, which must not hide the entries
that remain ahead of it.
+ final List<Integer> secondRemoval = new ArrayList<>();
+ map.removeEach(16, 19, (delivery) ->
secondRemoval.add(delivery.getDeliveryId()));
+
+ assertEquals(4, secondRemoval.size(), "Every delivery of the range
should have been removed: " + secondRemoval);
+ assertEquals(14, map.size(), "Only the deliveries covered by the range
should have been removed");
+
+ for (int i = 0; i < 4; i++) {
+ assertNotNull(map.get(i), "Delivery " + i + " is outside the range
and should still be tracked");
+ }
+ for (int i = 16; i < 20; i++) {
+ assertNull(map.get(i), "Delivery " + i + " is within the range and
should not be tracked");
+ }
+ for (int i = 20; i < 30; i++) {
+ assertNotNull(map.get(i), "Delivery " + i + " is outside the range
and should still be tracked");
+ }
+
+ final List<Integer> remaining = new ArrayList<>();
+ map.forEach(0, UnsignedInteger.MAX_VALUE.intValue(), (delivery) ->
remaining.add(delivery.getDeliveryId()));
+
+ assertEquals(14, remaining.size(), "Ranged visit should cover every
tracked delivery: " + remaining);
+
+ final List<Integer> lowSide = new ArrayList<>();
+ map.forEach(0, 19, (delivery) ->
lowSide.add(delivery.getDeliveryId()));
+
+ assertEquals(4, lowSide.size(), "Only the deliveries below the settled
range should be visited: " + lowSide);
+ for (int i = 0; i < 4; i++) {
+ assertTrue(lowSide.contains(i), "Delivery " + i + " is within the
range and should be visited: " + lowSide);
+ }
+
+ final List<Integer> emptyLowSide = new ArrayList<>();
+ map.forEach(4, 19, (delivery) ->
emptyLowSide.add(delivery.getDeliveryId()));
+
+ assertTrue(emptyLowSide.isEmpty(), "No delivery of the settled range
should be visited: " + emptyLowSide);
+ }
+
+ @Test
+ public void
testRangedForEachWhenWrappedRangeStraddlesTheOverflowOfAFullySettledEarlierGeneration()
{
+ final UnsettledMap<DeliveryType> map = createMap(5, 50);
+
+ final int PRE_WRAP_LAST_DELIVERY_ID =
UnsignedInteger.MAX_VALUE.intValue() - 15;
+ final int PRE_WRAP_FIRST_DELIVERY_ID = PRE_WRAP_LAST_DELIVERY_ID - 4;
+
+ // Deliveries of the generation that precedes the ID overflow,
followed by the deliveries
+ // that follow the overflow, and then every delivery of the earlier
generation is settled,
+ // which leaves the tracker holding only deliveries that follow the
overflow.
+ for (int i = PRE_WRAP_FIRST_DELIVERY_ID; i <=
PRE_WRAP_LAST_DELIVERY_ID; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+ for (int i = 0; i < 11; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+ for (int i = PRE_WRAP_FIRST_DELIVERY_ID; i <=
PRE_WRAP_LAST_DELIVERY_ID; i++) {
+ assertNotNull(map.remove(i), "Delivery before the overflow should
have been tracked: " + i);
+ }
+
+ assertEquals(11, map.size(), "Only the deliveries that follow the
overflow should remain tracked");
+
+ // The range straddles the overflow point so it covers [first ..
MAX_VALUE] and [0 .. 5].
+ // The earlier generation is gone and can match nothing in the first
half, but the tracked
+ // deliveries all fall inside the second half of the range.
+ for (int i = 0; i <= 5; i++) {
+ assertTrue(map.containsKey(i), "Delivery " + i + " should be
tracked before the ranged visit");
+ }
+
+ final List<Integer> visited = new ArrayList<>();
+ map.forEach(PRE_WRAP_LAST_DELIVERY_ID + 1, 5, (delivery) ->
visited.add(delivery.getDeliveryId()));
+
+ assertEquals(6, visited.size(), "Ranged visit should cover the tracked
deliveries that fall within"
+ + " the second half of the straddling range: " + visited);
+ for (int i = 0; i <= 5; i++) {
+ assertTrue(visited.contains(i), "Delivery " + i + " is within the
range and should be visited: " + visited);
+ }
+ assertEquals(11, map.size(), "forEach should not alter the tracker
contents");
+ }
+
+ @Test
+ public void
testRemoveEachWhenWrappedRangeStraddlesTheOverflowOfAFullySettledEarlierGeneration()
{
+ final UnsettledMap<DeliveryType> map = createMap(5, 50);
+
+ final int PRE_WRAP_LAST_DELIVERY_ID =
UnsignedInteger.MAX_VALUE.intValue() - 15;
+ final int PRE_WRAP_FIRST_DELIVERY_ID = PRE_WRAP_LAST_DELIVERY_ID - 4;
+
+ // Same layout as the forEach test above: deliveries that follow the
overflow are the only
+ // ones left unsettled once the generation that preceded the overflow
was settled.
+ for (int i = PRE_WRAP_FIRST_DELIVERY_ID; i <=
PRE_WRAP_LAST_DELIVERY_ID; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+ for (int i = 0; i < 11; i++) {
+ map.put(i, new DeliveryType(i));
+ }
+ for (int i = PRE_WRAP_FIRST_DELIVERY_ID; i <=
PRE_WRAP_LAST_DELIVERY_ID; i++) {
+ assertNotNull(map.remove(i), "Delivery before the overflow should
have been tracked: " + i);
+ }
+
+ assertEquals(11, map.size(), "Only the deliveries that follow the
overflow should remain tracked");
+
+ for (int i = 0; i <= 5; i++) {
+ assertTrue(map.containsKey(i), "Delivery " + i + " should be
tracked before the ranged removal");
+ }
+
+ final List<Integer> removed = new ArrayList<>();
+ map.removeEach(PRE_WRAP_LAST_DELIVERY_ID + 1, 5, (delivery) ->
removed.add(delivery.getDeliveryId()));
+
+ assertEquals(6, removed.size(), "Ranged removal should cover the
tracked deliveries that fall within"
+ + " the second half of the straddling range: " + removed);
+ for (int i = 0; i <= 5; i++) {
+ assertNull(map.get(i), "Delivery " + i + " is within the range and
should have been removed");
+ }
+ assertNotNull(map.get(6), "Deliveries past the end of the range should
still be tracked");
+ assertEquals(5, map.size(), "Only the deliveries covered by the range
should have been removed");
+ }
+
+ @Test
+ public void testForEachFirstRangeIsAllThatIsInMap() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 50);
+
+ map.put(UnsignedInteger.valueOf(10), new DeliveryType(10));
+ map.put(UnsignedInteger.valueOf(12), new DeliveryType(12));
+ map.put(UnsignedInteger.valueOf(14), new DeliveryType(14));
+
+ final List<Integer> removed = new ArrayList<>();
+
+ map.forEach(10, 5, d -> removed.add(d.getDeliveryId()));
+
+ assertEquals(3, removed.size());
+ assertTrue(removed.contains(10));
+ assertTrue(removed.contains(12));
+ assertTrue(removed.contains(14));
+ }
+
+ @Test
+ public void testRemoveEachClearFirstRange() {
+ final UnsettledMap<DeliveryType> map = createMap(5, 50);
+
+ map.put(UnsignedInteger.valueOf(10), new DeliveryType(10));
+ map.put(UnsignedInteger.valueOf(12), new DeliveryType(12));
+ map.put(UnsignedInteger.valueOf(14), new DeliveryType(14));
+
+ final List<Integer> removed = new ArrayList<>();
+
+ map.removeEach(10, 5, d -> removed.add(d.getDeliveryId()));
+
+ assertEquals(3, removed.size());
+ assertTrue(removed.contains(10));
+ assertTrue(removed.contains(12));
+ assertTrue(removed.contains(14));
+ }
+
+ //----- Iterator removal when the delivery ID series rolls over the
unsigned integer range
+
+ @Test
+ public void testValuesIteratorRemoveVisitsAllDeliveriesAfterIDOverflow() {
+ final UnsettledMap<DeliveryType> tracker = createMap(3, 4);
+
+ // One bucket of IDs that precede the ID series rolling over, then one
bucket of IDs that
+ // follow the overflow, which leaves the two buckets with overlapping
ID ranges.
+ for (int i = 10; i < 14; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+ for (int i = 5; i < 9; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+
+ assertEquals(8, tracker.size());
+
+ final List<Integer> visited = new ArrayList<>();
+ final Iterator<DeliveryType> iterator = tracker.values().iterator();
+
+ while (iterator.hasNext()) {
+ final DeliveryType delivery = iterator.next();
+
+ visited.add(delivery.getDeliveryId());
+
+ // ID 13 is the last entry of the first bucket, ID 5 the first
entry of the second.
+ if (delivery.getDeliveryId() == 13 || delivery.getDeliveryId() ==
5) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(Arrays.asList(10, 11, 12, 13, 5, 6, 7, 8), visited,
+ "Iteration should visit every delivery of both buckets: " +
visited);
+ assertEquals(6, tracker.size(), "Both selected deliveries should have
been removed");
+ assertNull(tracker.get(13), "Delivery removed from the bucket that
precedes the overflow should be gone");
+ assertNull(tracker.get(5), "Delivery removed from the bucket that
follows the overflow should be gone");
+
+ for (int i : new int[] { 10, 11, 12, 6, 7, 8 }) {
+ assertNotNull(tracker.get(i), "Delivery " + i + " should still be
tracked");
+ }
+ }
+
+ @Test
+ public void testKeysIteratorRemoveVisitsAllDeliveriesAfterIDOverflow() {
+ final UnsettledMap<DeliveryType> tracker = createMap(3, 4);
+
+ // IDs 10..13 precede the ID series rolling over, IDs 5..8 follow it.
+ for (int i = 10; i < 14; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+ for (int i = 5; i < 9; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+
+ assertEquals(8, tracker.size());
+
+ final List<Integer> visited = new ArrayList<>();
+ final Iterator<UnsignedInteger> iterator = tracker.keySet().iterator();
+
+ while (iterator.hasNext()) {
+ final UnsignedInteger key = iterator.next();
+ visited.add(key.intValue());
+
+ if (key.intValue() == 13 || key.intValue() == 5) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(Arrays.asList(10, 11, 12, 13, 5, 6, 7, 8), visited,
+ "Iteration should visit every key of both buckets: " + visited);
+ assertEquals(6, tracker.size(), "Both selected keys should have been
removed");
+ assertNull(tracker.get(13), "Key removed from the bucket that precedes
the overflow should be gone");
+ assertNull(tracker.get(5), "Key removed from the bucket that follows
the overflow should be gone");
+ }
+
+ @Test
+ public void testEntryIteratorRemoveVisitsAllDeliveriesAfterIDOverflow() {
+ final UnsettledMap<DeliveryType> tracker = createMap(3, 4);
+
+ // IDs 10..13 precede the ID series rolling over, IDs 5..8 follow it.
+ for (int i = 10; i < 14; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+ for (int i = 5; i < 9; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+
+ assertEquals(8, tracker.size());
+
+ final List<Integer> visited = new ArrayList<>();
+ final Iterator<Entry<UnsignedInteger, DeliveryType>> iterator =
tracker.entrySet().iterator();
+ while (iterator.hasNext()) {
+ final Entry<UnsignedInteger, DeliveryType> entry = iterator.next();
+ visited.add(entry.getKey().intValue());
+
+ if (entry.getKey().intValue() == 13 || entry.getKey().intValue()
== 5) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(Arrays.asList(10, 11, 12, 13, 5, 6, 7, 8), visited,
+ "Iteration should visit every entry of both buckets: " + visited);
+ assertEquals(6, tracker.size(), "Both selected entries should have
been removed");
+ assertNull(tracker.get(13), "Entry removed from the bucket that
precedes the overflow should be gone");
+ assertNull(tracker.get(5), "Entry removed from the bucket that follows
the overflow should be gone");
+ }
+
+ @Test
+ public void testValuesRemoveIfRemovesDeliveriesOnBothSidesOfIDOverflow() {
+ final UnsettledMap<DeliveryType> tracker = createMap(3, 4);
+
+ // IDs 10..13 precede the ID series rolling over, IDs 5..8 follow it.
+ for (int i = 10; i < 14; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+ for (int i = 5; i < 9; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+
+ assertEquals(8, tracker.size());
+
+ final boolean modified = tracker.values().removeIf(delivery -> {
+ return delivery.getDeliveryId() < 6 || delivery.getDeliveryId() ==
13;
+ });
+
+ assertTrue(modified, "Deliveries on both sides of the overflow should
have been removed");
+
+ assertEquals(6, tracker.size(), "Two deliveries should have been
removed");
+ assertNull(tracker.get(5), "Delivery removed before the overflow point
should be gone");
+ assertNull(tracker.get(13), "Delivery removed after the overflow point
should be gone");
+
+ for (int i : new int[] { 10, 11, 12, 6, 7, 8 }) {
+ assertNotNull(tracker.get(i), "Delivery " + i + " should still be
tracked");
+ }
+ }
+
+ @Test
+ public void
testValuesIteratorRemoveVisitsAllDeliveriesAfterIDOverflowWithDefaultBuckets() {
+ final UnsettledMap<DeliveryType> tracker = createMap(); // Default
bucket size of 256
+
+ // Two exactly filled buckets, the second one starting below the ID
the first one ended on.
+ final int firstIDBeforeOverflow = UnsignedInteger.MAX_VALUE.intValue()
- 255;
+ for (int i = 0; i < 256; i++) {
+ tracker.put(firstIDBeforeOverflow + i, new
DeliveryType(firstIDBeforeOverflow + i));
+ }
+ for (int i = 0; i < 256; i++) {
+ tracker.put(i, new DeliveryType(i));
+ }
+
+ assertEquals(512, tracker.size());
+
+ final int lastIDBeforeOverflow = UnsignedInteger.MAX_VALUE.intValue();
+ final Iterator<DeliveryType> iterator = tracker.values().iterator();
+
+ int visited = 0;
+
+ while (iterator.hasNext()) {
+ final DeliveryType delivery = iterator.next();
+ visited++;
+
+ if (delivery.getDeliveryId() == lastIDBeforeOverflow ||
delivery.getDeliveryId() == 0) {
+ iterator.remove();
+ }
+ }
+
+ assertEquals(512, visited, "Iteration should visit every delivery of
both buckets");
+ assertEquals(510, tracker.size(), "Both selected deliveries should
have been removed");
+ assertNull(tracker.get(lastIDBeforeOverflow), "Delivery removed before
the overflow point should be gone");
+ assertNull(tracker.get(0), "Delivery removed after the overflow point
should be gone");
+ assertNotNull(tracker.get(255), "Last delivery of the tracker should
still be tracked");
+ }
+
+ @Test
+ public void
testEveryTrackedDeliveryRemainsReachableAfterTheIDSeriesRollsBackwardsTwice() {
+ // Two deliveries per bucket so that a drained bucket is recycled
between the additions.
+ final UnsettledMap<DeliveryType> tracker = createMap(3, 2);
+ final int nearMaxId = Integer.MAX_VALUE;
+
+ // The second and third delivery make the ID series roll backwards,
which begins a new
+ // series of deliveries in its own bucket, the fourth joins the series
that precedes it.
+ tracker.put(nearMaxId + 3, new DeliveryType(nearMaxId + 3));
+ tracker.put(nearMaxId + 1, new DeliveryType(nearMaxId + 1));
+ tracker.put(nearMaxId - 4, new DeliveryType(nearMaxId - 4));
+ tracker.put(nearMaxId - 1, new DeliveryType(nearMaxId - 1));
+
+ // Draining the bucket of the first rolled back series recycles it,
and the next addition
+ // of that ID recycles the bucket it lands in when it is settled again.
+ assertNotNull(tracker.remove(nearMaxId + 1), "Delivery should have
been tracked");
+ tracker.put(nearMaxId + 1, new DeliveryType(nearMaxId + 1));
+ assertNotNull(tracker.remove(nearMaxId + 1), "Delivery should have
been tracked");
+
+ final List<DeliveryType> tracked = new ArrayList<>(tracker.values());
+ assertEquals(3, tracked.size(), "Every delivery that was not settled
should still be tracked");
+
+ // The tracker still knows the deliveries are unsettled so each of
them must remain
+ // reachable, otherwise no disposition can ever settle them.
+ for (DeliveryType delivery : tracked) {
+ final int deliveryId = delivery.getDeliveryId();
+ final String name = "delivery " +
UnsignedInteger.valueOf(deliveryId);
+ assertNotNull(tracker.get(deliveryId), "The " + name + " should be
reachable by its ID");
+ assertTrue(tracker.containsKey(deliveryId), "The " + name + "
should be tracked by its ID");
+ assertEquals(delivery, tracker.remove(deliveryId), "The " + name +
" should be settleable");
+ }
+
+ assertTrue(tracker.isEmpty(), "Settling every tracked delivery should
empty the tracker");
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]