io.activej.common.recycle.Recyclers Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of activej-common Show documentation
Show all versions of activej-common Show documentation
Various general utilities for ActiveJ project.
package io.activej.common.recycle;
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 io.activej.common.Utils.first;
import static java.util.Collections.singletonMap;
/**
* A registry of known {@link Recycler}s
*/
@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));
}
/**
* Registers a new recycler for some type
*
* @param type a class of object that will be recycled
* @param item a recycler for a given type
* @param a type of object that will be recycled
* @throws IllegalStateException if a recycler for a type already exists
* and is not equal to a given recycler
*/
public static synchronized 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);
}
}
}
/**
* Recycles a given object if there is a registered recycler for an object's class.
* Otherwise, does nothing
*
* @param object an object to be recycled
*/
public static void recycle(Object object) {
if (object == null) return;
//noinspection unchecked
Recycler