org.jhotdraw8.collection.spliterator.FailFastSpliterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of org.jhotdraw8.collection Show documentation
Show all versions of org.jhotdraw8.collection Show documentation
JHotDraw8 Utility classes for Collections
The newest version!
/*
* @(#)FailFastSpliterator.java
* Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.collection.spliterator;
import org.jspecify.annotations.Nullable;
import java.util.ConcurrentModificationException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
/**
* A spliterator that fails when a provided modification counter does not have an
* expected value.
*
* @param the element type
*/
public class FailFastSpliterator extends Spliterators.AbstractSpliterator {
private final Spliterator extends E> s;
private final int expectedModCount;
private final IntSupplier modCountSupplier;
public FailFastSpliterator(Spliterator extends E> s, IntSupplier modCountSupplier) {
super(s.estimateSize(), s.characteristics());
this.s = s;
this.modCountSupplier = modCountSupplier;
this.expectedModCount = modCountSupplier.getAsInt();
}
@Override
public boolean tryAdvance(Consumer super E> action) {
ensureUnmodified();
return s.tryAdvance(action);
}
protected void ensureUnmodified() {
if (expectedModCount != modCountSupplier.getAsInt()) {
throw new ConcurrentModificationException();
}
}
@Override
public @Nullable Spliterator trySplit() {
Spliterator extends E> split = s.trySplit();
return split == null ? null : new FailFastSpliterator<>(split, modCountSupplier);
}
@Override
public long estimateSize() {
return s.estimateSize();
}
@Override
public int characteristics() {
return s.characteristics() & ~Spliterator.IMMUTABLE;
}
}