Package com.github.trelawnm.weathersdk
Class WeatherCache
java.lang.Object
com.github.trelawnm.weathersdk.WeatherCache
Thread-safe LRU (Least Recently Used) cache for weather data with TTL support.
This cache maintains weather data for up to maxSize cities, automatically
evicting the least recently used entries when capacity is reached. Each cached
entry has a time-to-live (TTL) after which it is considered stale and requires
refresh from the API.
Features:
- Fixed size with LRU eviction policy
- TTL-based data freshness checking
- O(1) time complexity for get and put operations
- Thread-safe for concurrent access
Usage Example:
WeatherCache cache = new WeatherCache(10, Duration.ofMinutes(10));
// Store weather data
cache.put("London", weatherResponse);
// Retrieve weather data (updates access order)
WeatherResponse data = cache.get("London");
- Version:
- 1.0
- Author:
- trelawnm
- See Also:
-
WeatherCache.CachedWeatherDataWeatherResponse
-
Constructor Summary
ConstructorsConstructorDescriptionWeatherCache(int maxSize, Duration ttl) Constructs a new weather cache with specified capacity and TTL. -
Method Summary
Modifier and TypeMethodDescriptionvoidclear()Removes all entries from the cache.Retrieves weather data for the specified city.Returns all cities currently in cachevoidput(String city, WeatherResponse weatherData) Stores weather data for the specified city in the cache.intsize()Returns the current number of cities in the cache.
-
Constructor Details
-
WeatherCache
Constructs a new weather cache with specified capacity and TTL.- Parameters:
maxSize- the maximum number of cities to cache (must be positive)ttl- the time-to-live duration for cached entries (cannot be null)- Throws:
IllegalArgumentException- if maxSize is not positive or ttl is null
-
-
Method Details
-
get
Retrieves weather data for the specified city.If the data exists and is not stale, it updates the access order and returns the weather data. If the data is stale, it is removed from the cache and null is returned.
- Parameters:
city- the name of the city to look up- Returns:
- the cached weather data, or null if not found or stale
-
put
Stores weather data for the specified city in the cache.If the cache has reached maximum capacity, the least recently used city is automatically evicted. The new entry is added with current timestamps for creation time.
- Parameters:
city- the name of the city to cacheweatherData- the weather data to store- Throws:
IllegalArgumentException- if city is null or weatherData is null
-
size
public int size()Returns the current number of cities in the cache.- Returns:
- the number of cached cities
-
getAllCities
Returns all cities currently in cache- Returns:
- set of city names
-
clear
public void clear()Removes all entries from the cache.
-