要实现一个简单的Java缓存,可以使用`ConcurrentHashMap`和`ScheduledExecutorService`。以下是一个简单的示例:
```java
import java.util.concurrent.*;
public class SimpleCache<K, V> {
private final ConcurrentHashMap<K, CacheItem<V>> cache = new ConcurrentHashMap<>();
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
public void put(K key, V value, long expireTimeMillis) {
CacheItem<V> item = new CacheItem<>(value, System.currentTimeMillis() + expireTimeMillis);
cache.put(key, item);
executorService.schedule(() -> remove(key), expireTimeMillis, TimeUnit.MILLISECONDS);
}
public V get(K key) {
CacheItem<V> item = cache.get(key);
if (item == null || item.isExpired()) {
return null;
}
return item.getValue();
}
public void remove(K key) {
cache.remove(key);
}
private static class CacheItem<V> {
private final V value;
private final long expiryTime;
public CacheItem(V value, long expiryTime) {
this.value = value;
this.expiryTime = expiryTime;
}
public V getValue() {
return value;
}
public boolean isExpired() {
return System.currentTimeMillis() > expiryTime;
}
}
}
```
使用示例:
```java
public static void main(String[] args) throws InterruptedException {
SimpleCache<String, String> cache = new SimpleCache<>();
cache.put("key", "value", 5000); // 设置键为"key",值为"value",过期时间为5秒
System.out.println(cache.get("key")); // 输出"value"
Thread.sleep(6000); // 等待6秒
System.out.println(cache.get("key")); // 输出null,因为已经过期
}
```