Add a compare-and-swap reference wrapper and collections (#36)

* Add a compare-and-swap reference wrapper and collections

Useful for situations of very rare mutations and very frequent concurrent reads.

* Add some tests
This commit is contained in:
Raven Szewczyk authored and GitHub committed 2024-02-28 20:58:39 +00:00
1 parent 7be106da73
commit f6f993980e
4 files changed
+696

No files matched your search

@@ -0,0 +1,97 @@
package com.gtnewhorizon.gtnhlib.concurrent.cas;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;
/**
* A Compare-and-Swap adapter for any reference type. Extend it for your reference type, and implement the missing
* methods to use.
* <p>
* When you have a object that is read from very frequently, but mutated rarely, this class allows conveniently using it
* with reads as fast as an unsynchronized object, at the cost of writes that are much slower when they try to happen
* concurrently.
* <p>
* This works by wrapping an object into a {@link java.util.concurrent.atomic.AtomicReference}, and updating the
* reference with a new immutable copy of data every time it's updated. The data must not be null to avoid the ABA
* problem.
*
* @param <ImmutableView> The type of the stored reference, should be immutable (or at least not mutated by users)
* @param <MutableView> The type that's easy to construct from the stored reference, used for safe mutations.
*/
@SuppressWarnings("unused") // API type
public abstract class CasAdapter<ImmutableView, MutableView> {
private final AtomicReference<@NotNull ImmutableView> reference;
/** Initializes the inner reference to the given value. */
public CasAdapter(@NotNull ImmutableView initial) {
Objects.requireNonNull(initial);
this.reference = new AtomicReference<>(initial);
}
/** @return An immutable view of the stored object, do not mutate. */
public final @NotNull ImmutableView read() {
return reference.get();
}
/**
* Forcefully overwrites the contents with a new value, without checking the previous value. Only call if you know
* that any concurrent mutations are fine to occur on your new object instead of the old one.
*/
public final void overwrite(@NotNull ImmutableView newValue) {
Objects.requireNonNull(newValue);
// synchronize to avoid racing with this.mutate
synchronized (this) {
reference.set(newValue);
}
}
/**
* Creates a mutable copy of the inner data, runs the user-provided mutation function, and stores the new immutable
* data. Ensures the modification happens by using an atomic compare-and-set operation, and retrying the mutation on
* failure.
*
* @param mutator The function to modify the contents of this reference. Must be safe to invoke multiple times.
* @return The newly updated value.
*/
public final <R> R mutate(@NotNull Function<@NotNull MutableView, R> mutator) {
do {
// synchronize to avoid multiple racy CAS loops whenever possible
synchronized (this) {
final ImmutableView oldVal = reference.get();
final MutableView mutVal = mutableCopyOf(oldVal);
Objects.requireNonNull(mutVal);
final R retVal = mutator.apply(mutVal);
final ImmutableView newVal = immutableCopyOf(mutVal);
Objects.requireNonNull(newVal);
final boolean success = reference.compareAndSet(oldVal, newVal);
// Because of the synchronized block, this should always succeed - but future-proof with a CAS loop to
// be on the safe side
if (success) {
return retVal;
}
}
} while (true);
}
/**
* This function must create a mutable copy of the data stored in an immutable view. If the data is not a copy, this
* container is no longer thread-safe.
*
* @param data The immutable data
* @return The mutable data copy
*/
protected abstract @NotNull MutableView mutableCopyOf(@NotNull ImmutableView data);
/**
* This function must create an immutable copy of the data stored in a mutable view. If the data is not a copy, this
* container is no longer thread-safe if a mutable reference escapes from the mutate method.
*
* @param data The mutable data
* @return The immutable data copy
*/
protected abstract @NotNull ImmutableView immutableCopyOf(@NotNull MutableView data);
}
@@ -0,0 +1,328 @@
package com.gtnewhorizon.gtnhlib.concurrent.cas;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectImmutableList;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.ObjectList;
/**
* A fast-to-read, slow-to-modify concurrent ArrayList adapter, see {@link CasAdapter} for details on the
* implementation. Use {@link CasList#read()} and {@link CasList#mutate} if you need to perform any sequence of
* operations, otherwise each method call will operate on a different snapshot of the state of the list.
*
* @param <T> List element type
*/
@SuppressWarnings("unused") // API type
public class CasList<T> extends CasAdapter<ObjectImmutableList<T>, ObjectArrayList<T>> implements List<T> {
/** Constructs an empty list */
public CasList() {
super(ObjectImmutableList.of());
}
/** Constructs a list from the given elements, or an empty list if null */
@SafeVarargs
public CasList(final @Nullable T... initialElements) {
super(initialElements == null ? ObjectImmutableList.of() : new ObjectImmutableList<>(initialElements));
}
/** Constructs a list from the given elements, or an empty list if null */
public CasList(final @Nullable Collection<T> initialElements) {
super(initialElements == null ? ObjectImmutableList.of() : new ObjectImmutableList<>(initialElements));
}
/** Constructs a list from the given elements, or an empty list if null */
public CasList(final @Nullable ObjectIterator<T> initialElements) {
super(initialElements == null ? ObjectImmutableList.of() : new ObjectImmutableList<>(initialElements));
}
/** Constructs a list populated in the given lambda */
public CasList(final @NotNull Consumer<@NotNull ObjectArrayList<T>> constructor) {
this();
final ObjectArrayList<T> elems = new ObjectArrayList<>();
constructor.accept(elems);
overwrite(immutableCopyOf(elems));
}
@Override
public final @NotNull ObjectArrayList<T> mutableCopyOf(@NotNull ObjectImmutableList<T> data) {
return new ObjectArrayList<>(data);
}
@Override
public final @NotNull ObjectImmutableList<T> immutableCopyOf(@NotNull ObjectArrayList<T> data) {
return new ObjectImmutableList<>(data);
}
/**
* @deprecated Basically useless as it could be modified after being checked, iterate over a stored reference from
* {@link CasList#read()} instead.
*/
@Override
@Deprecated
public int size() {
return read().size();
}
@Override
public boolean isEmpty() {
return read().isEmpty();
}
@Override
public boolean contains(Object o) {
return read().contains(o);
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@NotNull
@Override
public Iterator<T> iterator() {
return read().iterator();
}
@NotNull
@Override
public Object @NotNull [] toArray() {
return read().toArray();
}
@NotNull
@Override
public <T1> T1 @NotNull [] toArray(@NotNull T1 @NotNull [] a) {
return read().toArray(a);
}
@Override
public boolean add(T t) {
mutate(al -> al.add(t));
return true;
}
@Override
public boolean remove(Object o) {
return mutate(al -> al.remove(o));
}
@Override
public boolean containsAll(@NotNull Collection<?> c) {
return read().containsAll(c);
}
@Override
public boolean addAll(@NotNull Collection<? extends T> c) {
return mutate(al -> al.addAll(c));
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public boolean addAll(int index, @NotNull Collection<? extends T> c) {
return mutate(al -> al.addAll(index, c));
}
@Override
public boolean removeAll(@NotNull Collection<?> c) {
return mutate(al -> al.removeAll(c));
}
@Override
public boolean retainAll(@NotNull Collection<?> c) {
return mutate(al -> al.retainAll(c));
}
@Override
public void clear() {
mutate(al -> {
al.clear();
return null;
});
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public T get(int index) {
return read().get(index);
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public T set(int index, T element) {
return mutate(al -> al.set(index, element));
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public void add(int index, T element) {
mutate(al -> {
al.add(index, element);
return null;
});
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public T remove(int index) {
return mutate(al -> al.remove(index));
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public int indexOf(Object o) {
return read().indexOf(o);
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@Override
@Deprecated
public int lastIndexOf(Object o) {
return read().lastIndexOf(o);
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@NotNull
@Override
public ListIterator<T> listIterator() {
return read().listIterator();
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@NotNull
@Override
public ListIterator<T> listIterator(int index) {
return read().listIterator(index);
}
/**
* @deprecated Indices are not safe to use across different method calls, use {@link CasList#mutate} or a cached
* {@link CasList#read} view instead.
*/
@NotNull
@Override
@Deprecated
public ObjectList<T> subList(int fromIndex, int toIndex) {
return read().subList(fromIndex, toIndex);
}
@Override
public void replaceAll(UnaryOperator<T> operator) {
mutate(al -> {
al.replaceAll(operator);
return null;
});
}
@Override
public void sort(Comparator<? super T> c) {
mutate(al -> {
al.sort(c);
return null;
});
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@Override
public Spliterator<T> spliterator() {
return read().spliterator();
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
return mutate(al -> al.removeIf(filter));
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@Override
public Stream<T> stream() {
return read().stream();
}
/**
* Note: the returned iterator will not see new/removed elements from after this method is called. The iterator is
* immutable.
*/
@Override
public Stream<T> parallelStream() {
return read().parallelStream();
}
@Override
public void forEach(Consumer<? super T> action) {
read().forEach(action);
}
@Override
public int hashCode() {
return read().hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List)) {
return false;
}
final ObjectImmutableList<T> myList = read();
final List<?> otherList = (obj instanceof CasList) ? ((CasList<?>) obj).read() : (List<?>) obj;
return myList.equals(otherList);
}
@Override
public String toString() {
return read().toString();
}
}
@@ -0,0 +1,238 @@
package com.gtnewhorizon.gtnhlib.concurrent.cas;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
/**
* A fast-to-read, slow-to-modify concurrent HashMap adapter, see {@link CasAdapter} for details on the implementation.
* Use {@link CasMap#read()} and {@link CasMap#mutate} if you need to perform any sequence of operations, otherwise each
* method call will operate on a different snapshot of the state of the map.
*
* @param <K> Map key type
* @param <V> Map value type
*/
@SuppressWarnings("unused") // API type
public class CasMap<K, V> extends CasAdapter<Map<K, V>, Object2ObjectOpenHashMap<K, V>> implements Map<K, V> {
/** Constructs an empty map */
public CasMap() {
super(Collections.unmodifiableMap(new Object2ObjectOpenHashMap<>()));
}
/** Constructs a new map with the given elements, or an empty map if null */
public CasMap(@Nullable Object2ObjectOpenHashMap<K, V> map) {
super(
Collections.unmodifiableMap(
map == null ? new Object2ObjectOpenHashMap<>() : new Object2ObjectOpenHashMap<>(map)));
}
/** Constructs a new map with the given keys and values arrays, or an empty map if null */
public CasMap(K @NotNull [] keys, V @NotNull [] values) {
super(Collections.unmodifiableMap(new Object2ObjectOpenHashMap<>(keys, values)));
}
/** Constructs a map populated in the given lambda */
public CasMap(final @NotNull Consumer<@NotNull Object2ObjectOpenHashMap<K, V>> constructor) {
this();
final Object2ObjectOpenHashMap<K, V> elems = new Object2ObjectOpenHashMap<>();
constructor.accept(elems);
overwrite(immutableCopyOf(elems));
}
@Override
public final @NotNull Object2ObjectOpenHashMap<K, V> mutableCopyOf(@NotNull Map<K, V> data) {
return new Object2ObjectOpenHashMap<>(data);
}
@Override
public final @NotNull Map<K, V> immutableCopyOf(@NotNull Object2ObjectOpenHashMap<K, V> data) {
// Protect against someone carrying a reference out of mutate() by copying again
return Collections.unmodifiableMap(new Object2ObjectOpenHashMap<>(data));
}
@Override
public V getOrDefault(Object key, V defaultValue) {
return read().getOrDefault(key, defaultValue);
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
mutate(m -> {
m.forEach(action);
return null;
});
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
mutate(m -> {
m.replaceAll(function);
return null;
});
}
@Nullable
@Override
public V putIfAbsent(K key, V value) {
final V oldValue = read().get(key);
if (oldValue != null) {
return oldValue;
}
return mutate(m -> m.putIfAbsent(key, value));
}
@Override
public boolean remove(Object key, Object value) {
@SuppressWarnings("SuspiciousMethodCalls")
final V presentValue = read().get(key);
if (!Objects.equals(value, presentValue)) {
return false;
}
return mutate(m -> m.remove(key, value));
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
final V presentValue = read().get(key);
if (!Objects.equals(oldValue, presentValue)) {
return false;
}
return mutate(m -> m.replace(key, oldValue, newValue));
}
@Nullable
@Override
public V replace(K key, V value) {
return mutate(m -> m.replace(key, value));
}
@Override
public V computeIfAbsent(K key, @NotNull Function<? super K, ? extends V> mappingFunction) {
final V oldValue = read().get(key);
if (oldValue != null) {
return oldValue;
}
return mutate(m -> m.computeIfAbsent(key, mappingFunction));
}
@Override
public V computeIfPresent(K key, @NotNull BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
final V oldValue = read().get(key);
if (oldValue == null) {
return null;
}
return mutate(m -> m.computeIfPresent(key, remappingFunction));
}
@Override
public V compute(K key, @NotNull BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return mutate(m -> m.compute(key, remappingFunction));
}
@Override
public V merge(K key, @NotNull V value, @NotNull BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
return mutate(m -> m.merge(key, value, remappingFunction));
}
@Override
public int size() {
return read().size();
}
@Override
public boolean isEmpty() {
return read().isEmpty();
}
@Override
public boolean containsKey(Object key) {
return read().containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return read().containsValue(value);
}
@Override
public V get(Object key) {
return read().get(key);
}
@Nullable
@Override
public V put(K key, V value) {
return mutate(m -> m.put(key, value));
}
@Override
public V remove(Object key) {
return mutate(m -> m.remove(key));
}
@Override
public void putAll(@NotNull Map<? extends K, ? extends V> other) {
mutate(m -> {
m.putAll(other);
return null;
});
}
@Override
public void clear() {
mutate(m -> {
m.clear();
return null;
});
}
@NotNull
@Override
public Set<K> keySet() {
return read().keySet();
}
@NotNull
@Override
public Collection<V> values() {
return read().values();
}
@NotNull
@Override
public Set<Entry<K, V>> entrySet() {
return read().entrySet();
}
@Override
public int hashCode() {
return read().hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Map)) {
return false;
}
final Map<K, V> myMap = read();
final Map<?, ?> otherMap = (obj instanceof CasMap) ? ((CasMap<?, ?>) obj).read() : (Map<?, ?>) obj;
return myMap.equals(otherMap);
}
@Override
public String toString() {
return read().toString();
}
}