import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class TimestampCache {
private final Map<String, Long> cache = new HashMap<>();
private final long cacheDuration;
public TimestampCache(long cacheDuration) {
this.cacheDuration = cacheDuration;
}
public long getTimestamp(String key) {
// Check if the timestamp is in the cache
if (cache.containsKey(key)) {
long timestamp = cache.get(key);
// Check if the timestamp is still valid
if (System.currentTimeMillis() - timestamp < cacheDuration) {
return timestamp; // Return cached timestamp
} else {
// Cache expired, remove it
cache.remove(key);
}
}
// If not in cache or expired, get the timestamp from the source
try {
return getTimestampFromSource(key);
} catch (Exception e) {
// Handle failure gracefully (e.g., log the error, return a default value)
System.err.println("Error fetching timestamp for key " + key + ": " + e.getMessage());
return -1; // Or another default value indicating failure
}
}
private long getTimestampFromSource(String key) throws Exception {
// Simulate fetching a timestamp from a source (e.g., a database, API)
// Replace this with your actual timestamp retrieval logic
System.out.println("Fetching timestamp from source for key: " + key);
return System.currentTimeMillis();
}
public void setTimestamp(String key, long timestamp) {
cache.put(key, timestamp); // Store timestamp in cache
}
public static void main(String[] args) throws Exception {
TimestampCache cache = new TimestampCache(10, TimeUnit.SECONDS);
// Example usage
long timestamp1 = cache.getTimestamp("key1");
System.out.println("Timestamp for key1: " + timestamp1);
long timestamp2 = cache.getTimestamp("key1"); // Should be from cache if within duration
System.out.println("Timestamp for key1 (again): " + timestamp2);
long timestamp3 = cache.getTimestamp("key2"); // New key, fetch from source
System.out.println("Timestamp for key2: " + timestamp3);
// Simulate fetching from source
cache.setTimestamp("key1", System.currentTimeMillis());
long timestamp4 = cache.getTimestamp("key1");
System.out.println("Timestamp for key1 (after set): " + timestamp4);
Thread.sleep(11000); // Wait for cache to expire
long timestamp5 = cache.getTimestamp("key1"); // Should fetch from source again
System.out.println("Timestamp for key1 (after expiration): " + timestamp5);
}
}
Add your comment