Created
October 5, 2023 14:57
Revisions
-
tinyzero4 created this gist
Oct 5, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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); } }