Bound SessionStore session cache to prevent unbounded memory growth

The cachedSessions HashMap grows with every unique (address, deviceId)
pair seen during message processing and is never evicted. In a
long-running daemon handling group messages, this causes linear memory
growth (~47 MB/hour observed) as SessionRecord objects accumulate for
every contact/device the daemon has ever communicated with.

Replace the unbounded HashMap with an LRU-bounded LinkedHashMap (access
order, max 1000 entries). Evicted sessions are reloaded from SQLite on
next access, so correctness is preserved.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHzM2XLKQoX9iraEdhoh3h
This commit is contained in:
Tony Cebzanov 2026-07-11 16:59:56 -04:00
parent 98d9960e66
commit 0c457a8629

View File

@ -18,7 +18,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -28,8 +28,15 @@ public class SessionStore implements SignalServiceSessionStore {
private static final String TABLE_SESSION = "session";
private static final Logger logger = LoggerFactory.getLogger(SessionStore.class);
private static final int MAX_CACHE_SIZE = 1000;
private final Map<Key, SessionRecord> cachedSessions = new HashMap<>();
private final Map<Key, SessionRecord> cachedSessions = new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Key, SessionRecord> eldest) {
return size() > MAX_CACHE_SIZE;
}
};
private final Database database;
private final int accountIdType;