diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasAdapter.java b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasAdapter.java new file mode 100644 index 00000000..43f0ae7c --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasAdapter.java @@ -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. + *

+ * 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. + *

+ * 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 The type of the stored reference, should be immutable (or at least not mutated by users) + * @param The type that's easy to construct from the stored reference, used for safe mutations. + */ +@SuppressWarnings("unused") // API type +public abstract class CasAdapter { + + 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 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); +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasList.java b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasList.java new file mode 100644 index 00000000..d55bb741 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasList.java @@ -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 List element type + */ +@SuppressWarnings("unused") // API type +public class CasList extends CasAdapter, ObjectArrayList> implements List { + + /** 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 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 initialElements) { + super(initialElements == null ? ObjectImmutableList.of() : new ObjectImmutableList<>(initialElements)); + } + + /** Constructs a list populated in the given lambda */ + public CasList(final @NotNull Consumer<@NotNull ObjectArrayList> constructor) { + this(); + final ObjectArrayList elems = new ObjectArrayList<>(); + constructor.accept(elems); + overwrite(immutableCopyOf(elems)); + } + + @Override + public final @NotNull ObjectArrayList mutableCopyOf(@NotNull ObjectImmutableList data) { + return new ObjectArrayList<>(data); + } + + @Override + public final @NotNull ObjectImmutableList immutableCopyOf(@NotNull ObjectArrayList 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 iterator() { + return read().iterator(); + } + + @NotNull + @Override + public Object @NotNull [] toArray() { + return read().toArray(); + } + + @NotNull + @Override + public 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 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 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 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 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 subList(int fromIndex, int toIndex) { + return read().subList(fromIndex, toIndex); + } + + @Override + public void replaceAll(UnaryOperator operator) { + mutate(al -> { + al.replaceAll(operator); + return null; + }); + } + + @Override + public void sort(Comparator 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 spliterator() { + return read().spliterator(); + } + + @Override + public boolean removeIf(Predicate 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 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 parallelStream() { + return read().parallelStream(); + } + + @Override + public void forEach(Consumer 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 myList = read(); + final List otherList = (obj instanceof CasList) ? ((CasList) obj).read() : (List) obj; + return myList.equals(otherList); + } + + @Override + public String toString() { + return read().toString(); + } +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasMap.java b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasMap.java new file mode 100644 index 00000000..3abd5d6b --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/concurrent/cas/CasMap.java @@ -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 Map key type + * @param Map value type + */ +@SuppressWarnings("unused") // API type +public class CasMap extends CasAdapter, Object2ObjectOpenHashMap> implements Map { + + /** 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 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> constructor) { + this(); + final Object2ObjectOpenHashMap elems = new Object2ObjectOpenHashMap<>(); + constructor.accept(elems); + overwrite(immutableCopyOf(elems)); + } + + @Override + public final @NotNull Object2ObjectOpenHashMap mutableCopyOf(@NotNull Map data) { + return new Object2ObjectOpenHashMap<>(data); + } + + @Override + public final @NotNull Map immutableCopyOf(@NotNull Object2ObjectOpenHashMap 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 action) { + mutate(m -> { + m.forEach(action); + return null; + }); + } + + @Override + public void replaceAll(BiFunction 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 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 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 remappingFunction) { + return mutate(m -> m.compute(key, remappingFunction)); + } + + @Override + public V merge(K key, @NotNull V value, @NotNull BiFunction 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 other) { + mutate(m -> { + m.putAll(other); + return null; + }); + } + + @Override + public void clear() { + mutate(m -> { + m.clear(); + return null; + }); + } + + @NotNull + @Override + public Set keySet() { + return read().keySet(); + } + + @NotNull + @Override + public Collection values() { + return read().values(); + } + + @NotNull + @Override + public Set> 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 myMap = read(); + final Map otherMap = (obj instanceof CasMap) ? ((CasMap) obj).read() : (Map) obj; + return myMap.equals(otherMap); + } + + @Override + public String toString() { + return read().toString(); + } +} diff --git a/src/test/java/com/gtnewhorizon/gtnhlib/test/concurrent/CasTest.java b/src/test/java/com/gtnewhorizon/gtnhlib/test/concurrent/CasTest.java new file mode 100644 index 00000000..5297e395 --- /dev/null +++ b/src/test/java/com/gtnewhorizon/gtnhlib/test/concurrent/CasTest.java @@ -0,0 +1,33 @@ +package com.gtnewhorizon.gtnhlib.test.concurrent; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import com.gtnewhorizon.gtnhlib.concurrent.cas.CasList; +import com.gtnewhorizon.gtnhlib.concurrent.cas.CasMap; + +// A few sanity checks for the CAS structures. +public class CasTest { + + @Test + void simpleCasList() { + final CasList intList = new CasList<>(1, 2, 3); + for (int i = 4; i <= 10; i++) { + intList.add(i); + } + Assertions.assertEquals(10, intList.read().size()); + Assertions.assertArrayEquals(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, intList.toArray(new Integer[0])); + } + + @Test + void simpleCasMap() { + final CasMap intMap = new CasMap<>(new Integer[] { 1, 2, 3 }, new Integer[] { 2, 4, 6 }); + for (int i = 4; i <= 10; i++) { + intMap.put(i, i * 2); + } + Assertions.assertEquals(10, intMap.read().size()); + for (int i = 1; i <= 10; i++) { + Assertions.assertEquals(i * 2, intMap.get(i)); + } + } +}