From: AsamK Date: Thu, 27 Feb 2025 15:41:59 +0000 (+0100) Subject: Add in-memory cache to KeyValueStore X-Git-Tag: v0.13.13~4 X-Git-Url: https://git.nmode.ca/signal-cli/commitdiff_plain/141d3326abd5cfa71db3c53c36a71efedbb69733 Add in-memory cache to KeyValueStore --- diff --git a/lib/src/main/java/org/asamk/signal/manager/storage/keyValue/KeyValueStore.java b/lib/src/main/java/org/asamk/signal/manager/storage/keyValue/KeyValueStore.java index e9338afc..2f59c9d2 100644 --- a/lib/src/main/java/org/asamk/signal/manager/storage/keyValue/KeyValueStore.java +++ b/lib/src/main/java/org/asamk/signal/manager/storage/keyValue/KeyValueStore.java @@ -10,6 +10,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import java.util.HashMap; import java.util.Objects; public class KeyValueStore { @@ -18,6 +19,7 @@ public class KeyValueStore { private static final Logger logger = LoggerFactory.getLogger(KeyValueStore.class); private final Database database; + private final HashMap, Object> cache = new HashMap<>(); public static void createSql(Connection connection) throws SQLException { // When modifying the CREATE statement here, also add a migration in AccountDatabase.java @@ -36,7 +38,14 @@ public class KeyValueStore { this.database = database; } + @SuppressWarnings("unchecked") public T getEntry(KeyValueEntry key) { + synchronized (cache) { + if (cache.containsKey(key)) { + logger.trace("Got entry for key {} from cache", key.key()); + return (T) cache.get(key); + } + } try (final var connection = database.getConnection()) { return getEntry(connection, key); } catch (SQLException e) { @@ -63,11 +72,17 @@ public class KeyValueStore { try (final var statement = connection.prepareStatement(sql)) { statement.setString(1, key.key()); - final var result = Utils.executeQueryForOptional(statement, - resultSet -> readValueFromResultSet(key, resultSet)).orElse(null); + var result = Utils.executeQueryForOptional(statement, resultSet -> readValueFromResultSet(key, resultSet)) + .orElse(null); if (result == null) { - return key.defaultValue(); + logger.trace("Got entry for key {} from default value", key.key()); + result = key.defaultValue(); + } else { + logger.trace("Got entry for key {} from db", key.key()); + } + synchronized (cache) { + cache.put(key, result); } return result; } @@ -95,6 +110,9 @@ public class KeyValueStore { setParameterValue(statement, 2, key.clazz(), value); statement.executeUpdate(); } + synchronized (cache) { + cache.put(key, value); + } return true; }