1. import java.util.*;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. public class ResourceSync {
  5. private final Map<String, List<Object>> resources = new HashMap<>(); // Store resources by name
  6. private final Map<String, Integer> resourceCounts = new HashMap<>(); // Track resource counts
  7. private final int maxRate = 10; // Maximum rate of synchronization
  8. private final int sleepMillis = 100; // Sleep duration between syncs
  9. private final Semaphore semaphore = new Semaphore(maxRate); // Rate limiter
  10. private final AtomicInteger syncCount = new AtomicInteger(0); //Sync counter
  11. public void addResource(String name, List<?> resource) {
  12. resources.put(name, resource);
  13. resourceCounts.put(name, 0);
  14. }
  15. public List<?> getResource(String name) {
  16. return resources.get(name);
  17. }
  18. public synchronized int getResourceCount(String name) {
  19. return resourceCounts.getOrDefault(name, 0);
  20. }
  21. public synchronized void incrementResourceCount(String name) {
  22. resourceCounts.put(name, resourceCounts.get(name) + 1);
  23. }
  24. public synchronized void resetResourceCount(String name) {
  25. resourceCounts.put(name, 0);
  26. }
  27. public void syncResources() throws InterruptedException {
  28. semaphore.acquire(); // Acquire a permit from the rate limiter
  29. try {
  30. for (Map.Entry<String, List<?>> entry : resources.entrySet()) {
  31. String name = entry.getKey();
  32. List<?> resourceList = entry.getValue();
  33. // Simulate resource synchronization (e.g., updating data)
  34. synchronized (resourceList) {
  35. // Perform synchronization operations on the resource list
  36. // Example: Increment a counter in the resource
  37. incrementResourceCount(name);
  38. }
  39. }
  40. syncCount.incrementAndGet();
  41. } finally {
  42. semaphore.release(); // Release the permit when done
  43. }
  44. }
  45. public static void main(String[] args) throws InterruptedException {
  46. ResourceSync sync = new ResourceSync();
  47. // Add some resources
  48. sync.addResource("resource1", Arrays.asList(1, 2, 3));
  49. sync.addResource("resource2", Arrays.asList("a", "b", "c"));
  50. // Simulate scheduled runs
  51. for (int i = 0; i < 5; i++) {
  52. System.out.println("Syncing resources... (Sync count: " + sync.syncCount + ")");
  53. sync.syncResources();
  54. Thread.sleep(sync.sleepMillis);
  55. }
  56. System.out.println("All syncs completed.");
  57. }
  58. }

Add your comment