1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.TimeUnit;
  4. public class TimestampCache {
  5. private final Map<String, Long> cache = new HashMap<>();
  6. private final long cacheDuration;
  7. public TimestampCache(long cacheDuration) {
  8. this.cacheDuration = cacheDuration;
  9. }
  10. public long getTimestamp(String key) {
  11. // Check if the timestamp is in the cache
  12. if (cache.containsKey(key)) {
  13. long timestamp = cache.get(key);
  14. // Check if the timestamp is still valid
  15. if (System.currentTimeMillis() - timestamp < cacheDuration) {
  16. return timestamp; // Return cached timestamp
  17. } else {
  18. // Cache expired, remove it
  19. cache.remove(key);
  20. }
  21. }
  22. // If not in cache or expired, get the timestamp from the source
  23. try {
  24. return getTimestampFromSource(key);
  25. } catch (Exception e) {
  26. // Handle failure gracefully (e.g., log the error, return a default value)
  27. System.err.println("Error fetching timestamp for key " + key + ": " + e.getMessage());
  28. return -1; // Or another default value indicating failure
  29. }
  30. }
  31. private long getTimestampFromSource(String key) throws Exception {
  32. // Simulate fetching a timestamp from a source (e.g., a database, API)
  33. // Replace this with your actual timestamp retrieval logic
  34. System.out.println("Fetching timestamp from source for key: " + key);
  35. return System.currentTimeMillis();
  36. }
  37. public void setTimestamp(String key, long timestamp) {
  38. cache.put(key, timestamp); // Store timestamp in cache
  39. }
  40. public static void main(String[] args) throws Exception {
  41. TimestampCache cache = new TimestampCache(10, TimeUnit.SECONDS);
  42. // Example usage
  43. long timestamp1 = cache.getTimestamp("key1");
  44. System.out.println("Timestamp for key1: " + timestamp1);
  45. long timestamp2 = cache.getTimestamp("key1"); // Should be from cache if within duration
  46. System.out.println("Timestamp for key1 (again): " + timestamp2);
  47. long timestamp3 = cache.getTimestamp("key2"); // New key, fetch from source
  48. System.out.println("Timestamp for key2: " + timestamp3);
  49. // Simulate fetching from source
  50. cache.setTimestamp("key1", System.currentTimeMillis());
  51. long timestamp4 = cache.getTimestamp("key1");
  52. System.out.println("Timestamp for key1 (after set): " + timestamp4);
  53. Thread.sleep(11000); // Wait for cache to expire
  54. long timestamp5 = cache.getTimestamp("key1"); // Should fetch from source again
  55. System.out.println("Timestamp for key1 (after expiration): " + timestamp5);
  56. }
  57. }

Add your comment