import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DataNormalizer {
private final ConcurrentHashMap<String, String> dataCache = new ConcurrentHashMap<>();
private final int timeoutSeconds;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public DataNormalizer(int timeoutSeconds) {
this.timeoutSeconds = timeoutSeconds;
scheduleCleanup();
}
// Method to normalize incoming data
public String normalizeData(String key, String data) {
// If data already exists in cache, check if it's expired
if (dataCache.containsKey(key)) {
String cachedData = dataCache.get(key);
if (isExpired(cachedData)) {
// Remove expired data
dataCache.remove(key);
return null; // Or handle expired data differently
} else {
return cachedData; // Return cached data
}
}
// Normalize the data (example normalization - convert to lowercase)
String normalizedData = data.toLowerCase();
// Store the normalized data in the cache with a timeout
dataCache.put(key, normalizedData);
return normalizedData;
}
private boolean isExpired(String data) {
long lastUpdated = System.currentTimeMillis() - dataCache.get(data).length();
return lastUpdated > (timeoutSeconds * 1000);
}
// Schedule a task to clean up expired data periodically
private void scheduleCleanup() {
scheduler.scheduleAtFixedRate(() -> {
// Remove expired data from the cache
dataCache.entrySet().removeIf(entry -> isExpired(entry.getValue()));
System.out.println("Data cleanup completed."); // Log cleanup
}, 0, timeoutSeconds, TimeUnit.SECONDS);
}
// Shutdown the scheduler when the DataNormalizer is no longer needed
public void shutdown() {
scheduler.shutdown();
}
public static void main(String[] args) throws InterruptedException {
DataNormalizer normalizer = new DataNormalizer(5); // Timeout of 5 seconds
String data1 = "Hello World";
String normalized1 = normalizer.normalizeData("key1", data1);
System.out.println("Normalized data1: " + normalized1);
String data2 = "HELLO WORLD";
String normalized2 = normalizer.normalizeData("key1", data2);
System.out.println("Normalized data2: " + normalized2);
// Wait for a few seconds to simulate data arriving later
Thread.sleep(6000); // Wait for data to expire
String data3 = "HELLO WORLD";
String normalized3 = normalizer.normalizeData("key1", data3);
System.out.println("Normalized data3: " + normalized3);
normalizer.shutdown();
}
}
Add your comment