limit life-time for cached serial ports #6713

This commit is contained in:
kifir 2024-08-15 12:43:08 +03:00 committed by rusefillc
parent 859ddd23b5
commit 42e2e75a9e
1 changed files with 31 additions and 4 deletions

View File

@ -2,6 +2,8 @@ package com.rusefi;
import com.devexperts.logging.Logging;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@ -11,15 +13,26 @@ import java.util.Set;
public class SerialPortCache {
private final static Logging log = Logging.getLogging(SerialPortCache.class);
private final static Duration lifeTime = Duration.ofSeconds(2);
private final Map<String, SerialPortScanner.PortResult> cachedPorts = new HashMap<>();
private final Map<String, CachedPort> cachedPorts = new HashMap<>();
Optional<SerialPortScanner.PortResult> get(final String serialPort) {
return Optional.ofNullable(cachedPorts.get(serialPort));
final CachedPort cachedPort = cachedPorts.get(serialPort);
if (cachedPort != null) {
if (cachedPort.isExpired()) {
cachedPorts.remove(serialPort);
log.info("Expired port is removed: " + serialPort);
} else {
return Optional.of(cachedPort.port);
}
}
return Optional.empty();
}
void put(final SerialPortScanner.PortResult port) {
cachedPorts.put(port.port, port);
cachedPorts.put(port.port, new CachedPort(port));
}
void retainAll(final Set<String> serialPortsToRetain) {
@ -36,7 +49,21 @@ public class SerialPortCache {
// two steps to avoid ConcurrentModificationException
toRemove.forEach(p -> {
cachedPorts.remove(p);
log.info("Removing port " + p);
log.info("Disappeared port is removed: " + p);
});
}
private static class CachedPort {
private final SerialPortScanner.PortResult port;
private final Instant expirationTimestamp;
CachedPort(final SerialPortScanner.PortResult portToCache) {
this.port = portToCache;
this.expirationTimestamp = Instant.now().plus(lifeTime);
}
boolean isExpired() {
return expirationTimestamp.isBefore(Instant.now());
}
}
}