|
| 1 | +# TTLHashMap |
| 2 | + |
| 3 | +TTLHashMap is a Java library that provides a thread-safe hash map implementation with support for time-to-live (TTL) entries. This data structure is useful for caching scenarios where you want entries to automatically expire after a specified duration. |
| 4 | + |
| 5 | +## Features |
| 6 | + |
| 7 | +- Thread-safe operations using `ConcurrentHashMap` |
| 8 | +- Configurable time-to-live (TTL) for entries |
| 9 | +- Automatic removal of expired entries |
| 10 | +- Support for custom actions when entries expire |
| 11 | +- Flexible TTL units (seconds, minutes, hours, etc.) |
| 12 | + |
| 13 | +## Usage |
| 14 | + |
| 15 | +Here's a quick example of how to use TTLHashMap: |
| 16 | + |
| 17 | +```java |
| 18 | +import com.athingforcode.TTLHashMap; |
| 19 | +import java.util.concurrent.TimeUnit; |
| 20 | + |
| 21 | +public class Example { |
| 22 | + public static void main(String[] args) { |
| 23 | + TTLHashMap<String, String> map = new TTLHashMap<>(); |
| 24 | + |
| 25 | + // Add an entry that expires after 5 seconds |
| 26 | + map.put("key1", "value1", 5, TimeUnit.SECONDS, (k, v) -> System.out.println("Expired: " + k + " = " + v)); |
| 27 | + |
| 28 | + // Add a non-expiring entry |
| 29 | + map.put("key2", "value2", -1, TimeUnit.SECONDS, null); |
| 30 | + |
| 31 | + // Retrieve a value |
| 32 | + String value = map.get("key1"); |
| 33 | + |
| 34 | + // Remove an entry |
| 35 | + map.remove("key2"); |
| 36 | + |
| 37 | + // Don't forget to shut down the map when you're done |
| 38 | + map.shutdown(); |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +## API Reference |
| 44 | + |
| 45 | +### `TTLHashMap<K, V>` |
| 46 | + |
| 47 | +- `TTLHashMap()`: Constructs a new TTLHashMap. |
| 48 | +- `void put(K key, V value, long ttl, TimeUnit unit, BiConsumer<K, V> actionWhenExpired)`: Puts a key-value pair into the map with an optional expiration time and expiration action. |
| 49 | +- `V get(K key)`: Retrieves the value associated with the specified key. |
| 50 | +- `void remove(K key)`: Removes the mapping for the specified key from this map if present. |
| 51 | +- `void shutdown()`: Shuts down the TTLHashMap and its scheduler. |
| 52 | + |
| 53 | +## License |
| 54 | + |
| 55 | +Apache License 2.0 |
| 56 | + |
| 57 | + |
0 commit comments