diff --git a/src/main/java/slimeknights/mantle/util/NonnullBiConsumer.java b/src/main/java/slimeknights/mantle/util/NonnullBiConsumer.java new file mode 100644 index 0000000..155a740 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/NonnullBiConsumer.java @@ -0,0 +1,14 @@ +package slimeknights.mantle.util; + +import javax.annotation.Nonnull; +import java.util.function.BiConsumer; + +/** + * Equivalent to {@link BiConsumer}, except with nonnull contract. + * + * @see BiConsumer + */ +@FunctionalInterface +public interface NonnullBiConsumer { + void accept(@Nonnull T t, @Nonnull U u); +} diff --git a/src/main/java/slimeknights/mantle/util/WeakConsumerWrapper.java b/src/main/java/slimeknights/mantle/util/WeakConsumerWrapper.java new file mode 100644 index 0000000..8d1090b --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/WeakConsumerWrapper.java @@ -0,0 +1,35 @@ +package slimeknights.mantle.util; + +import net.minecraftforge.common.util.NonNullConsumer; + +import java.lang.ref.WeakReference; + +/** + * Implementation of {@link NonNullConsumer} that weakly references a parent object. + * Designed for use in {@link net.minecraftforge.common.util.LazyOptional#addListener(NonNullConsumer)}, + * to prevent the capability owner from keeping a reference to the listener TE and preventing garbage collection. + * @param Parent object type, typically a TE + * @param Consumer value + */ +public class WeakConsumerWrapper implements NonNullConsumer { + private final WeakReference te; + private final NonnullBiConsumer consumer; + + /** + * Creates a new weak consumer wrapper + * @param te Weak reference, typically to a TE + * @param consumer Consumer using the TE and the consumed value. Should not use a lambda reference to an object that may need to be garbage collected + */ + public WeakConsumerWrapper(TE te, NonnullBiConsumer consumer) { + this.te = new WeakReference<>(te); + this.consumer = consumer; + } + + @Override + public void accept(C c) { + TE te = this.te.get(); + if (te != null) { + consumer.accept(te, c); + } + } +}