From d267dd1dda606f0c56d8afaa7187485e60ebfd86 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Thu, 28 Nov 2024 17:32:28 -0500 Subject: move replica2 to top level --- src/main/java/derms/replica2/Resources.java | 74 +++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/derms/replica2/Resources.java (limited to 'src/main/java/derms/replica2/Resources.java') diff --git a/src/main/java/derms/replica2/Resources.java b/src/main/java/derms/replica2/Resources.java new file mode 100644 index 0000000..634e315 --- /dev/null +++ b/src/main/java/derms/replica2/Resources.java @@ -0,0 +1,74 @@ +package derms.replica2; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentHashMap; + +class Resources { + private Map> resources; + + Resources() { + this.resources = new ConcurrentHashMap>(); + } + + List borrowed(CoordinatorID borrower, ResourceType name) { + List borrowed = new ArrayList(); + Resource[] namedResources = getByName(name); + for (Resource r : namedResources) { + if (r.isBorrowed && r.borrower.equals(borrower)) { + borrowed.add(r); + } + } + return borrowed; + } + + Resource getByID(ResourceID id) throws NoSuchElementException { + for (Map rids : resources.values()) { + Resource resource = rids.get(id); + if (resource != null) { + return resource; + } + } + throw new NoSuchElementException("No such resource "+id); + } + + Resource[] getByName(ResourceType name) { + Map rids = resources.get(name); + if (rids == null) { + return new Resource[0]; + } + Resource[] r = new Resource[0]; + return rids.values().toArray(r); + } + + void add(Resource r) { + Map rids; + synchronized (resources) { + rids = resources.get(r.type); + if (rids == null) { + rids = new ConcurrentHashMap(); + resources.put(r.type, rids); + } + } + synchronized (rids) { + Resource existing = rids.get(r.id); + if (existing != null) { + existing.duration += r.duration; + } else { + rids.put(r.id, r); + } + } + } + + void removeByID(ResourceID id) throws NoSuchElementException { + for (Map rids : resources.values()) { + if (rids.containsKey(id)) { + rids.remove(id); + return; + } + } + throw new NoSuchElementException("No such resource "+id); + } +} -- cgit v1.2.3