Skip to content
Snippets Groups Projects
Commit 3aab4603 authored by Robert Goldmann's avatar Robert Goldmann
Browse files

MultiCacheKeyService must be thread safe

parent d0fe3da9
No related branches found
No related tags found
No related merge requests found
import abc
import threading
from abc import ABC
from dataclasses import dataclass
from datetime import datetime
......@@ -14,18 +15,22 @@ class CacheEntry:
cachedData: Dict
lock = threading.Lock()
class MultiCacheKeyService(ABC):
def __init__(self):
self._cache = {}
def get_data(self, cacheKey: str, fetchIntervalInSeconds: int, settings: Dict) -> Dict:
if cacheKey not in self._cache:
self._cache[cacheKey] = CacheEntry(cacheKey, fetchIntervalInSeconds, settings, 0, {})
cacheEntry = self._cache[cacheKey]
if self.__is_data_obsolete(cacheEntry):
cacheEntry.cachedData = self._fetch_data(cacheEntry.settings)
return cacheEntry.cachedData
with lock:
if cacheKey not in self._cache:
self._cache[cacheKey] = CacheEntry(cacheKey, fetchIntervalInSeconds, settings, 0, {})
cacheEntry = self._cache[cacheKey]
if self.__is_data_obsolete(cacheEntry):
cacheEntry.cachedData = self._fetch_data(cacheEntry.settings)
return cacheEntry.cachedData
def __is_data_obsolete(self, cacheEntry: CacheEntry) -> bool:
now = datetime.now().timestamp()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment