1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.ConcurrentHashMap;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.TimeUnit;
  7. public class DataNormalizer {
  8. private final ConcurrentHashMap<String, String> dataCache = new ConcurrentHashMap<>();
  9. private final int timeoutSeconds;
  10. private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  11. public DataNormalizer(int timeoutSeconds) {
  12. this.timeoutSeconds = timeoutSeconds;
  13. scheduleCleanup();
  14. }
  15. // Method to normalize incoming data
  16. public String normalizeData(String key, String data) {
  17. // If data already exists in cache, check if it's expired
  18. if (dataCache.containsKey(key)) {
  19. String cachedData = dataCache.get(key);
  20. if (isExpired(cachedData)) {
  21. // Remove expired data
  22. dataCache.remove(key);
  23. return null; // Or handle expired data differently
  24. } else {
  25. return cachedData; // Return cached data
  26. }
  27. }
  28. // Normalize the data (example normalization - convert to lowercase)
  29. String normalizedData = data.toLowerCase();
  30. // Store the normalized data in the cache with a timeout
  31. dataCache.put(key, normalizedData);
  32. return normalizedData;
  33. }
  34. private boolean isExpired(String data) {
  35. long lastUpdated = System.currentTimeMillis() - dataCache.get(data).length();
  36. return lastUpdated > (timeoutSeconds * 1000);
  37. }
  38. // Schedule a task to clean up expired data periodically
  39. private void scheduleCleanup() {
  40. scheduler.scheduleAtFixedRate(() -> {
  41. // Remove expired data from the cache
  42. dataCache.entrySet().removeIf(entry -> isExpired(entry.getValue()));
  43. System.out.println("Data cleanup completed."); // Log cleanup
  44. }, 0, timeoutSeconds, TimeUnit.SECONDS);
  45. }
  46. // Shutdown the scheduler when the DataNormalizer is no longer needed
  47. public void shutdown() {
  48. scheduler.shutdown();
  49. }
  50. public static void main(String[] args) throws InterruptedException {
  51. DataNormalizer normalizer = new DataNormalizer(5); // Timeout of 5 seconds
  52. String data1 = "Hello World";
  53. String normalized1 = normalizer.normalizeData("key1", data1);
  54. System.out.println("Normalized data1: " + normalized1);
  55. String data2 = "HELLO WORLD";
  56. String normalized2 = normalizer.normalizeData("key1", data2);
  57. System.out.println("Normalized data2: " + normalized2);
  58. // Wait for a few seconds to simulate data arriving later
  59. Thread.sleep(6000); // Wait for data to expire
  60. String data3 = "HELLO WORLD";
  61. String normalized3 = normalizer.normalizeData("key1", data3);
  62. System.out.println("Normalized data3: " + normalized3);
  63. normalizer.shutdown();
  64. }
  65. }

Add your comment