1. import java.util.Collection;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import java.util.concurrent.ConcurrentHashMap;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ScheduledExecutorService;
  7. import java.util.concurrent.TimeUnit;
  8. import java.util.logging.Logger;
  9. public class CollectionWatcher {
  10. private final Logger logger = Logger.getLogger(CollectionWatcher.class.getName());
  11. private final ConcurrentHashMap<Collection<?>, Object> collectionStates = new ConcurrentHashMap<>(); // Stores collection states
  12. private final Set<Collection<?>> watchedCollections = new HashSet<>(); // Keeps track of watched collections
  13. private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  14. private final long checkIntervalMillis;
  15. public CollectionWatcher(long checkIntervalMillis) {
  16. this.checkIntervalMillis = checkIntervalMillis;
  17. }
  18. public void watchCollection(Collection<?> collection) {
  19. if (collection == null) {
  20. logger.severe("Cannot watch a null collection.");
  21. return;
  22. }
  23. watchedCollections.add(collection);
  24. collectionStates.put(collection, collection); // Initial state
  25. }
  26. public void stopWatching() {
  27. scheduler.shutdown();
  28. }
  29. public void startWatching() {
  30. scheduler.scheduleAtFixedRate(this::checkCollections, 0, checkIntervalMillis, TimeUnit.MILLISECONDS);
  31. }
  32. private void checkCollections() {
  33. for (Collection<?> collection : watchedCollections) {
  34. try {
  35. Collection<?> currentCollection = collectionStates.get(collection);
  36. if (currentCollection == null) {
  37. logger.warning("Collection " + collection + " not found. Possibly removed.");
  38. continue;
  39. }
  40. if (!collection.equals(currentCollection)) {
  41. logger.info("Collection " + collection + " changed.");
  42. collectionStates.put(collection, collection); // Update the state
  43. }
  44. } catch (Exception e) {
  45. logger.severe("Error checking collection " + collection + ": " + e.getMessage());
  46. }
  47. }
  48. }
  49. public static void main(String[] args) throws InterruptedException {
  50. CollectionWatcher watcher = new CollectionWatcher(1000); // Check every 1 second
  51. // Example Usage
  52. Collection<String> collection1 = new HashSet<>();
  53. collection1.add("item1");
  54. watcher.watchCollection(collection1);
  55. Collection<Integer> collection2 = new HashSet<>();
  56. collection2.add(1);
  57. collection2.add(2);
  58. watcher.watchCollection(collection2);
  59. watcher.startWatching();
  60. Thread.sleep(5000); // Run for 5 seconds
  61. watcher.stopWatching();
  62. }
  63. }

Add your comment