import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class CollectionWatcher {
private final Logger logger = Logger.getLogger(CollectionWatcher.class.getName());
private final ConcurrentHashMap<Collection<?>, Object> collectionStates = new ConcurrentHashMap<>(); // Stores collection states
private final Set<Collection<?>> watchedCollections = new HashSet<>(); // Keeps track of watched collections
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final long checkIntervalMillis;
public CollectionWatcher(long checkIntervalMillis) {
this.checkIntervalMillis = checkIntervalMillis;
}
public void watchCollection(Collection<?> collection) {
if (collection == null) {
logger.severe("Cannot watch a null collection.");
return;
}
watchedCollections.add(collection);
collectionStates.put(collection, collection); // Initial state
}
public void stopWatching() {
scheduler.shutdown();
}
public void startWatching() {
scheduler.scheduleAtFixedRate(this::checkCollections, 0, checkIntervalMillis, TimeUnit.MILLISECONDS);
}
private void checkCollections() {
for (Collection<?> collection : watchedCollections) {
try {
Collection<?> currentCollection = collectionStates.get(collection);
if (currentCollection == null) {
logger.warning("Collection " + collection + " not found. Possibly removed.");
continue;
}
if (!collection.equals(currentCollection)) {
logger.info("Collection " + collection + " changed.");
collectionStates.put(collection, collection); // Update the state
}
} catch (Exception e) {
logger.severe("Error checking collection " + collection + ": " + e.getMessage());
}
}
}
public static void main(String[] args) throws InterruptedException {
CollectionWatcher watcher = new CollectionWatcher(1000); // Check every 1 second
// Example Usage
Collection<String> collection1 = new HashSet<>();
collection1.add("item1");
watcher.watchCollection(collection1);
Collection<Integer> collection2 = new HashSet<>();
collection2.add(1);
collection2.add(2);
watcher.watchCollection(collection2);
watcher.startWatching();
Thread.sleep(5000); // Run for 5 seconds
watcher.stopWatching();
}
}
Add your comment