io.activej.common.recycle.Recyclers Maven / Gradle / Ivy
package io.activej.common.recycle;
import io.activej.common.collection.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.Collections.singletonMap;
@SuppressWarnings("unchecked")
public class Recyclers {
private static final Recycler> NO_RECYCLER = item -> {};
private static final Map, Recycler>> REGISTRY = new HashMap<>();
private static final ConcurrentHashMap, Recycler>> CACHED_RECYCLERS = new ConcurrentHashMap<>();
static {
register(Recyclable.class, Recyclable::recycle);
register(AutoCloseable.class, Recyclers::recycleCloseable);
register(List.class, Recyclers::recycleList);
register(Map.class, Recyclers::recycleMap);
register(Optional.class, optional -> optional.ifPresent(Recyclers::recycle));
register(CompletionStage.class, future -> future.thenAccept(Recyclers::recycle));
}
synchronized public static void register(Class type, Recycler item) {
REGISTRY.put(type, item);
for (Map.Entry, Recycler>> entry : CACHED_RECYCLERS.entrySet()) {
Class> cachedType = entry.getKey();
Recycler> cachedRecyclerOld = entry.getValue();
Recycler> cachedRecyclerNew = lookup(cachedType);
if (!cachedRecyclerOld.equals(cachedRecyclerNew)) {
throw new IllegalStateException("Changed recycler for " + type + " in cache entry " + cachedType);
}
}
}
public static void recycle(Object object) {
if (object == null) return;
//noinspection unchecked
Recycler