Skip to content

Instantly share code, notes, and snippets.

@tinyzero4
Created October 5, 2023 14:57

Revisions

  1. tinyzero4 created this gist Oct 5, 2023.
    49 changes: 49 additions & 0 deletions Tracker.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentSkipListSet;
    import java.util.concurrent.atomic.AtomicInteger;

    import static java.lang.Integer.parseInt;
    import static java.util.Objects.requireNonNull;

    public class Tracker {

    private final ConcurrentHashMap<String, AtomicInteger> byTypeCounters = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, ConcurrentSkipListSet<Integer>> byTypeDeAllocations = new ConcurrentHashMap<>();

    public String allocate(String hostType) {
    requireNonNull(hostType);
    if (hostType.isBlank()) throw new IllegalArgumentException("hostType should not be blank");

    Integer nextVersion = null;

    var deallocations = byTypeDeAllocations.get(hostType);
    if (deallocations != null) {
    nextVersion = deallocations.pollFirst();
    }

    if (nextVersion == null) {
    var byTypeCounter = byTypeCounters.getOrDefault(hostType, new AtomicInteger(0));
    nextVersion = byTypeCounter.incrementAndGet();
    byTypeCounters.put(hostType, byTypeCounter);
    }

    return hostType + ":" + nextVersion;
    }

    public void deallocate(String hostname) {
    requireNonNull(hostname);
    if (hostname.isBlank()) throw new IllegalArgumentException("hostname should not be blank");

    var parts = hostname.split(":");
    if (parts.length != 2) throw new IllegalArgumentException("invalid hostname definition");

    var hostType = parts[0];
    var version = parseInt(parts[1]);

    var deallocations = byTypeDeAllocations.getOrDefault(hostType, new ConcurrentSkipListSet<>());
    deallocations.add(version);
    byTypeDeAllocations.put(hostType, deallocations);

    }

    }