import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ResourceSync {
private final Map<String, List<Object>> resources = new HashMap<>(); // Store resources by name
private final Map<String, Integer> resourceCounts = new HashMap<>(); // Track resource counts
private final int maxRate = 10; // Maximum rate of synchronization
private final int sleepMillis = 100; // Sleep duration between syncs
private final Semaphore semaphore = new Semaphore(maxRate); // Rate limiter
private final AtomicInteger syncCount = new AtomicInteger(0); //Sync counter
public void addResource(String name, List<?> resource) {
resources.put(name, resource);
resourceCounts.put(name, 0);
}
public List<?> getResource(String name) {
return resources.get(name);
}
public synchronized int getResourceCount(String name) {
return resourceCounts.getOrDefault(name, 0);
}
public synchronized void incrementResourceCount(String name) {
resourceCounts.put(name, resourceCounts.get(name) + 1);
}
public synchronized void resetResourceCount(String name) {
resourceCounts.put(name, 0);
}
public void syncResources() throws InterruptedException {
semaphore.acquire(); // Acquire a permit from the rate limiter
try {
for (Map.Entry<String, List<?>> entry : resources.entrySet()) {
String name = entry.getKey();
List<?> resourceList = entry.getValue();
// Simulate resource synchronization (e.g., updating data)
synchronized (resourceList) {
// Perform synchronization operations on the resource list
// Example: Increment a counter in the resource
incrementResourceCount(name);
}
}
syncCount.incrementAndGet();
} finally {
semaphore.release(); // Release the permit when done
}
}
public static void main(String[] args) throws InterruptedException {
ResourceSync sync = new ResourceSync();
// Add some resources
sync.addResource("resource1", Arrays.asList(1, 2, 3));
sync.addResource("resource2", Arrays.asList("a", "b", "c"));
// Simulate scheduled runs
for (int i = 0; i < 5; i++) {
System.out.println("Syncing resources... (Sync count: " + sync.syncCount + ")");
sync.syncResources();
Thread.sleep(sync.sleepMillis);
}
System.out.println("All syncs completed.");
}
}
Add your comment