import time
import threading
class CacheInvalidator:
def __init__(self, timeout):
self.timeout = timeout
self.cache = {}
self.lock = threading.Lock()
def invalidate(self, key):
"""Invalidates the cache entry for the given key."""
with self.lock:
if key in self.cache:
del self.cache[key]
print(f"Invalidated cache entry for key: {key}")
return True
else:
return False
def is_valid(self, key):
"""Checks if the cache entry for the given key is still valid."""
with self.lock:
if key in self.cache:
if time.time() - self.cache[key]['timestamp'] < self.timeout:
return True
else:
del self.cache[key]
print(f"Cache entry for key: {key} expired.")
return False
else:
return False
def set(self, key, value):
"""Sets a cache entry with a timestamp."""
with self.lock:
self.cache[key] = {'value': value, 'timestamp': time.time()}
Add your comment