All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.lambdacube.aspecio.internal.service.ServicePool Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
package io.lambdacube.aspecio.internal.service;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Supplier;

public final class ServicePool {

    private final Map originalToProxy = new IdentityHashMap<>();
    private final Map proxyToOriginal = new IdentityHashMap<>();
    private final Map proxyToCount = new IdentityHashMap<>();

    public synchronized T get(Object originalService, Supplier proxyFactory) {
        T proxy = originalToProxy.computeIfAbsent(originalService, k -> proxyFactory.get());
        proxyToOriginal.putIfAbsent(proxy, originalService);
        proxyToCount.compute(proxy, (k, v) -> {
            if (v == null) {
                return 1;
            } else {
                return v + 1;
            }
        });
        return proxy;
    }

    public synchronized boolean unget(T proxy) {
        Integer count = proxyToCount.compute(proxy, (k, v) -> {
            if (v == null) {
                return 0;
            } else {
                return v - 1;
            }
        });

        if (count > 0) {
            return false;
        }
        // clean-up
        proxyToCount.remove(proxy);
        Object original = proxyToOriginal.remove(proxy);
        T proxyX = originalToProxy.remove(original);

        assert proxy == proxyX;

        return true;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy