1. import time
  2. import threading
  3. class CacheInvalidator:
  4. def __init__(self, timeout):
  5. self.timeout = timeout
  6. self.cache = {}
  7. self.lock = threading.Lock()
  8. def invalidate(self, key):
  9. """Invalidates the cache entry for the given key."""
  10. with self.lock:
  11. if key in self.cache:
  12. del self.cache[key]
  13. print(f"Invalidated cache entry for key: {key}")
  14. return True
  15. else:
  16. return False
  17. def is_valid(self, key):
  18. """Checks if the cache entry for the given key is still valid."""
  19. with self.lock:
  20. if key in self.cache:
  21. if time.time() - self.cache[key]['timestamp'] < self.timeout:
  22. return True
  23. else:
  24. del self.cache[key]
  25. print(f"Cache entry for key: {key} expired.")
  26. return False
  27. else:
  28. return False
  29. def set(self, key, value):
  30. """Sets a cache entry with a timestamp."""
  31. with self.lock:
  32. self.cache[key] = {'value': value, 'timestamp': time.time()}

Add your comment