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

io.funtom.util.concurrent.ConcurrencySegment Maven / Gradle / Ivy

There is a newer version: 0.2
Show newest version
package io.funtom.util.concurrent;

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

final class ConcurrencySegment {

    private final Map store = new HashMap();
    private final Supplier valuesSupplier;

    ConcurrencySegment(Supplier valuesSupplier) {
        this.valuesSupplier = valuesSupplier;
    }

    synchronized V getValue(K key) {
        Entry current = store.get(key);
        if (current == null) {
            current = new Entry();
            store.put(key, current);
        } else {
            current.users++;
        }
        return current.value;
    }

    synchronized void releaseKey(K key) {
        Entry current = store.get(key);
        if (current.users == 1) {
            store.remove(key);
        } else {
            current.users--;
        }
    }

    private class Entry {
        private int users = 1;
        private V value = valuesSupplier.get();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy