Import chronicle-map cache implementation from GerritForge repo

Initial import from GerritForge repository[1]

https://review.gerrithub.io/admin/repos/GerritForge/modules_cache-chroniclemap

Change-Id: Ic12ab467e0d46b1d2a1e059108416ececc188624
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a1c2a23
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,23 @@
+# Compiled class file
+*.class
+
+# Log file
+*.log
+
+# BlueJ files
+*.ctxt
+
+# Mobile Tools for Java (J2ME)
+.mtj.tmp/
+
+# Package Files #
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+
+# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
+hs_err_pid*
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..2336593
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,48 @@
+load("//tools/bzl:junit.bzl", "junit_tests")
+load("//javatests/com/google/gerrit/acceptance:tests.bzl", "acceptance_tests")
+
+load(
+    "//tools/bzl:plugin.bzl",
+    "PLUGIN_DEPS",
+    "PLUGIN_TEST_DEPS",
+    "gerrit_plugin",
+)
+
+gerrit_plugin(
+    name = "cache-chroniclemap",
+    srcs = glob(["src/main/java/**/*.java"]),
+    resources = glob(["src/main/resources/**/*"]),
+    deps = [
+        "@chronicle-map//jar",
+        "@chronicle-core//jar",
+        "@chronicle-wire//jar",
+        "@chronicle-bytes//jar",
+        "@chronicle-algo//jar",
+        "@chronicle-values//jar",
+        "@chronicle-threads//jar",
+        "@javapoet//jar",
+        "@jna-platform//jar",
+        "@dev-jna//jar",
+    ],
+)
+
+junit_tests(
+    name = "cache-chroniclemap_tests",
+    srcs = glob(
+        ["src/test/java/**/*Test.java"],
+    ),
+    visibility = ["//visibility:public"],
+    deps = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+        ":cache-chroniclemap__plugin",
+        "@chronicle-bytes//jar",
+    ],
+)
+
+acceptance_tests(
+    srcs = glob(["src/test/java/**/*IT.java"]),
+    group = "server_cache",
+    labels = ["server"],
+    deps = [
+        ":cache-chroniclemap__plugin",
+    ],
+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2befb1a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,26 @@
+# Persistent cache for Gerrit, based on ChronicleMap
+
+Non-blocking and super-fast on-disk cache libModule for [Gerrit Code Review](https://gerritcodereview.com)
+based on [ChronicleMap on-disk implementation](https://github.com/OpenHFT/Chronicle-Map).
+
+## How to build
+
+This libModule is built like a Gerrit in-tree plugin, using Bazelisk. See the
+[build instructions](build.md) for more details.
+
+
+## Setup
+
+* Install cache-chronicalmap module
+
+Install the chronicle-map module into the `$GERRIT_SITE/lib` directory.
+
+Add the cache-chroniclemap module to `$GERRIT_SITE/etc/gerrit.config` as follows:
+
+```
+[gerrit]
+  installModule = com.googlesource.gerrit.modules.cache.chroniclemap.ChronicleMapCacheModule
+```
+
+For further information and supported options, refer to [config](config.md)
+documentation.
\ No newline at end of file
diff --git a/build.md b/build.md
new file mode 100644
index 0000000..3782de5
--- /dev/null
+++ b/build.md
@@ -0,0 +1,37 @@
+# Build
+
+This plugin is built with Bazel in-tree build.
+
+## Build in Gerrit tree
+
+Create a symbolic link of the repsotiory source to the Gerrit source
+tree /plugins/cache-chronicalmap directory, and the external_plugin_deps.bzl
+dependencies linked to /plugins/external_plugin_deps.bzl.
+
+Example:
+
+```sh
+git clone https://gerrit.googlesource.com/gerrit
+git clone https://github.com/GerritForge/modules_cache-chroniclemap.git
+cd gerrit/plugins
+ln -s ../../modules_cache-chroniclemap cache-chroniclemap
+ln -sf ../../external_plugin_deps.bzl .
+```
+
+From the Gerrit source tree issue the command `bazelsk build plugins/cache-chroniclemap`.
+
+Example:
+
+```sh
+bazelisk build plugins/cache-chroniclemap
+```
+
+The libModule jar file is created under `basel-bin/plugins/cache-chroniclemap/cache-chroniclemap.jar`
+
+To execute the tests run `bazelisk test plugins/cache-chroniclemap/...` from the Gerrit source tree.
+
+Example:
+
+```sh
+bazelisk test plugins/cache-chroniclemap/...
+```
\ No newline at end of file
diff --git a/config.md b/config.md
new file mode 100644
index 0000000..5bbea2b
--- /dev/null
+++ b/config.md
@@ -0,0 +1,47 @@
+Configuration
+=============
+
+Global configuration of the cache-chroniclemap libModule is done in the `gerrit.config` file in the
+site's etc directory.
+
+Information about gerrit caches mechanism can be found in the relevant
+[documentation section](https://charm.cs.illinois.edu/gerrit/Documentation/config-gerrit.html#cache).
+
+Chronicle-map supports most of the cache configuration parameters, such as:
+
+* `maxAge`: Maximum age to keep an entry in the cache.
+[Gerrit docs](https://gerrit-review.googlesource.com/Documentation/config-gerrit.html#cache.name.maxAge)
+
+* `refreshAfterWrite`: Duration after which we asynchronously refresh the cached value.
+[Gerrit docs](https://gerrit-review.googlesource.com/Documentation/config-gerrit.html#cache.name.refreshAfterWrite)
+
+Chronicle-map implementation however might require some additional configuration
+
+## Configuration parameters
+
+```cache.<name>.avgKeySize```
+:   The average number of bytes to be allocated for the key of this cache.
+If key is a boxed primitive type, a value interface or Byteable subclass, i. e.
+if key size is known statically, it is automatically accounted by chronicle-map.
+In this case, this value will be ignored.
+
+[Official docs](
+https://www.javadoc.io/doc/net.openhft/chronicle-map/3.8.0/net/openhft/chronicle/map/ChronicleMapBuilder.html#averageKeySize-double-
+)
+
+```cache.<name>.avgValueSize```
+:   The average number of bytes to be allocated for a value of this cache.
+If key is a boxed primitive type, a value interface or Byteable subclass, i. e.
+if key size is known statically, it is automatically accounted by chronicle-map.
+In this case, this value will be ignored.
+
+[Official docs](
+https://www.javadoc.io/doc/net.openhft/chronicle-map/3.8.0/net/openhft/chronicle/map/ChronicleMapBuilder.html#averageValueSize-double-
+)
+
+```cache.<name>.entries```
+: The number of entries that this cache is going to hold, _at most_
+
+[Official docs](
+https://www.javadoc.io/doc/net.openhft/chronicle-map/3.8.0/net/openhft/chronicle/map/ChronicleMapBuilder.html#entries-long-
+)
\ No newline at end of file
diff --git a/external_plugin_deps.bzl b/external_plugin_deps.bzl
new file mode 100644
index 0000000..06f1fd9
--- /dev/null
+++ b/external_plugin_deps.bzl
@@ -0,0 +1,64 @@
+load("//tools/bzl:maven_jar.bzl", "maven_jar")
+
+# Ensure artifacts compatibility by selecting them from the Bill Of Materials
+# https://search.maven.org/artifact/net.openhft/chronicle-bom/2.19.283/pom
+def external_plugin_deps():
+    maven_jar(
+        name = "chronicle-map",
+        artifact = "net.openhft:chronicle-map:3.19.40",
+        sha1 = "820edb9aad86adb2a836b4f66a878d6101bbee54",
+    )
+
+    maven_jar(
+        name = "chronicle-core",
+        artifact = "net.openhft:chronicle-core:2.19.50",
+        sha1 = "71234f0116eceda4034cddceb79cd924cea5c4be",
+    )
+
+    maven_jar(
+        name = "chronicle-wire",
+        artifact = "net.openhft:chronicle-wire:2.19.45",
+        sha1 = "1ec0da34391b57a3c1809b1e139caf0371784bc4",
+    )
+
+    maven_jar(
+        name = "chronicle-bytes",
+        artifact = "net.openhft:chronicle-bytes:2.19.46",
+        sha1 = "790a1c374f008f97202dd94ec8435edfce798cd0",
+    )
+
+    maven_jar(
+        name = "chronicle-algo",
+        artifact = "net.openhft:chronicle-algorithms:2.19.40",
+        sha1 = "9445d2c48468a32c54d631e3908c4362a2bbac2c",
+    )
+
+    maven_jar(
+        name = "chronicle-values",
+        artifact = "net.openhft:chronicle-values:2.19.41",
+        sha1 = "f8bb874bbd67ceabd5166510043b5473e66285f4",
+    )
+
+    maven_jar(
+        name = "chronicle-threads",
+        artifact = "net.openhft:chronicle-threads:2.19.47",
+        sha1 = "ef25ab51b795551e4c7bf3f80acde9b5364a3641",
+    )
+
+    maven_jar(
+        name = "javapoet",
+        artifact = "com.squareup:javapoet:1.12.1",
+        sha1 = "e0e49f502697522ef047470b117ff81edc9f9a07",
+    )
+
+    maven_jar(
+        name = "jna-platform",
+        artifact = "net.java.dev.jna:jna-platform:5.5.0",
+        sha1 = "af38e7c4d0fc73c23ecd785443705bfdee5b90bf",
+    )
+
+    maven_jar(
+        name = "dev-jna",
+        artifact = "net.java.dev.jna:jna:5.5.0",
+        sha1 = "0e0845217c4907822403912ad6828d8e0b256208",
+    )
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfig.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfig.java
new file mode 100644
index 0000000..cb345aa
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfig.java
@@ -0,0 +1,141 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.server.config.ConfigUtil;
+import com.google.gerrit.server.config.GerritServerConfig;
+import com.google.gerrit.server.config.SitePaths;
+import com.google.inject.assistedinject.Assisted;
+import com.google.inject.assistedinject.AssistedInject;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import org.eclipse.jgit.lib.Config;
+
+public class ChronicleMapCacheConfig {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+  private final File persistedFile;
+  private final long diskLimit;
+  private final long maxEntries;
+  private final long averageKeySize;
+  private final long averageValueSize;
+  private final Duration expireAfterWrite;
+  private final Duration refreshAfterWrite;
+
+  public static final long DEFAULT_MAX_ENTRIES = 1000;
+
+  public static final long DEFAULT_AVG_KEY_SIZE = 128;
+  public static final long DEFAULT_AVG_VALUE_SIZE = 2048;
+
+  public interface Factory {
+    ChronicleMapCacheConfig create(
+        @Assisted("Name") String name,
+        @Assisted("ConfigKey") String configKey,
+        @Assisted("DiskLimit") long diskLimit,
+        @Nullable @Assisted("ExpireAfterWrite") Duration expireAfterWrite,
+        @Nullable @Assisted("RefreshAfterWrite") Duration refreshAfterWrite);
+  }
+
+  @AssistedInject
+  ChronicleMapCacheConfig(
+      @GerritServerConfig Config cfg,
+      SitePaths site,
+      @Assisted("Name") String name,
+      @Assisted("ConfigKey") String configKey,
+      @Assisted("DiskLimit") long diskLimit,
+      @Nullable @Assisted("ExpireAfterWrite") Duration expireAfterWrite,
+      @Nullable @Assisted("RefreshAfterWrite") Duration refreshAfterWrite) {
+    final Path cacheDir = getCacheDir(site, cfg.getString("cache", null, "directory"));
+    this.persistedFile =
+        cacheDir != null ? cacheDir.resolve(String.format("%s.dat", name)).toFile() : null;
+    this.diskLimit = cfg.getLong("cache", configKey, "diskLimit", diskLimit);
+
+    this.maxEntries = cfg.getLong("cache", configKey, "maxEntries", DEFAULT_MAX_ENTRIES);
+    this.averageKeySize = cfg.getLong("cache", configKey, "avgKeySize", DEFAULT_AVG_KEY_SIZE);
+    this.averageValueSize = cfg.getLong("cache", configKey, "avgValueSize", DEFAULT_AVG_VALUE_SIZE);
+    this.expireAfterWrite =
+        Duration.ofSeconds(
+            ConfigUtil.getTimeUnit(
+                cfg, "cache", configKey, "maxAge", toSeconds(expireAfterWrite), SECONDS));
+    this.refreshAfterWrite =
+        Duration.ofSeconds(
+            ConfigUtil.getTimeUnit(
+                cfg,
+                "cache",
+                configKey,
+                "refreshAfterWrite",
+                toSeconds(refreshAfterWrite),
+                SECONDS));
+  }
+
+  public Duration getExpireAfterWrite() {
+    return expireAfterWrite;
+  }
+
+  public Duration getRefreshAfterWrite() {
+    return refreshAfterWrite;
+  }
+
+  public long getMaxEntries() {
+    return maxEntries;
+  }
+
+  public File getPersistedFile() {
+    return persistedFile;
+  }
+
+  public long getAverageKeySize() {
+    return averageKeySize;
+  }
+
+  public long getAverageValueSize() {
+    return averageValueSize;
+  }
+
+  public long getDiskLimit() {
+    return diskLimit;
+  }
+
+  private static Path getCacheDir(SitePaths site, String name) {
+    if (name == null) {
+      return null;
+    }
+    Path loc = site.resolve(name);
+    if (!Files.exists(loc)) {
+      try {
+        Files.createDirectories(loc);
+      } catch (IOException e) {
+        logger.atWarning().log("Can't create disk cache: %s", loc.toAbsolutePath());
+        return null;
+      }
+    }
+    if (!Files.isWritable(loc)) {
+      logger.atWarning().log("Can't write to disk cache: %s", loc.toAbsolutePath());
+      return null;
+    }
+    logger.atFine().log("Enabling disk cache %s", loc.toAbsolutePath());
+    return loc;
+  }
+
+  private static long toSeconds(@Nullable Duration duration) {
+    return duration != null ? duration.getSeconds() : 0;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheFactory.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheFactory.java
new file mode 100644
index 0000000..929c1c6
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheFactory.java
@@ -0,0 +1,134 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.flogger.FluentLogger;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.extensions.registration.DynamicMap;
+import com.google.gerrit.server.cache.CacheBackend;
+import com.google.gerrit.server.cache.PersistentCacheDef;
+import com.google.gerrit.server.cache.PersistentCacheFactory;
+import com.google.gerrit.server.logging.LoggingContextAwareScheduledExecutorService;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+@Singleton
+class ChronicleMapCacheFactory implements PersistentCacheFactory, LifecycleListener {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+  private final ChronicleMapCacheConfig.Factory configFactory;
+  private final DynamicMap<Cache<?, ?>> cacheMap;
+  private final List<ChronicleMapCacheImpl<?, ?>> caches;
+  private final ScheduledExecutorService cleanup;
+
+  @Inject
+  ChronicleMapCacheFactory(
+      ChronicleMapCacheConfig.Factory configFactory, DynamicMap<Cache<?, ?>> cacheMap) {
+    this.configFactory = configFactory;
+    this.caches = new LinkedList<>();
+    this.cacheMap = cacheMap;
+    this.cleanup =
+        new LoggingContextAwareScheduledExecutorService(
+            Executors.newScheduledThreadPool(
+                1,
+                new ThreadFactoryBuilder()
+                    .setNameFormat("ChronicleMap-Prune-%d")
+                    .setDaemon(true)
+                    .build()));
+  }
+
+  @SuppressWarnings({"unchecked"})
+  @Override
+  public <K, V> Cache<K, V> build(PersistentCacheDef<K, V> in, CacheBackend backend) {
+    ChronicleMapCacheConfig config =
+        configFactory.create(
+            in.name(),
+            in.configKey(),
+            in.diskLimit(),
+            in.expireAfterWrite(),
+            in.refreshAfterWrite());
+    ChronicleMapCacheImpl<K, V> cache = null;
+    try {
+      cache = new ChronicleMapCacheImpl<>(in, config, null);
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+    synchronized (caches) {
+      caches.add(cache);
+    }
+    return cache;
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public <K, V> LoadingCache<K, V> build(
+      PersistentCacheDef<K, V> in, CacheLoader<K, V> loader, CacheBackend backend) {
+    ChronicleMapCacheConfig config =
+        configFactory.create(
+            in.name(),
+            in.configKey(),
+            in.diskLimit(),
+            in.expireAfterWrite(),
+            in.refreshAfterWrite());
+    ChronicleMapCacheImpl<K, V> cache = null;
+    try {
+      cache = new ChronicleMapCacheImpl<>(in, config, loader);
+    } catch (IOException e) {
+      throw new UncheckedIOException(e);
+    }
+    synchronized (caches) {
+      caches.add(cache);
+    }
+    return cache;
+  }
+
+  @Override
+  public void onStop(String plugin) {
+    synchronized (caches) {
+      for (Map.Entry<String, Provider<Cache<?, ?>>> entry : cacheMap.byPlugin(plugin).entrySet()) {
+        Cache<?, ?> cache = entry.getValue().get();
+        if (caches.remove(cache)) {
+          ((ChronicleMapCacheImpl<?, ?>) cache).close();
+        }
+      }
+    }
+  }
+
+  @Override
+  public void start() {
+    for (ChronicleMapCacheImpl<?, ?> cache : caches) {
+      if (!cache.getConfig().getExpireAfterWrite().isZero()) {
+        cleanup.scheduleWithFixedDelay(cache::prune, 30, 30, TimeUnit.SECONDS);
+      }
+    }
+  }
+
+  @Override
+  public void stop() {
+    cleanup.shutdownNow();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheImpl.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheImpl.java
new file mode 100644
index 0000000..c90381d
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheImpl.java
@@ -0,0 +1,219 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.common.cache.AbstractLoadingCache;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.CacheStats;
+import com.google.gerrit.server.cache.PersistentCache;
+import com.google.gerrit.server.cache.PersistentCacheDef;
+import com.google.gerrit.server.util.time.TimeUtil;
+import java.io.IOException;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.LongAdder;
+import net.openhft.chronicle.map.ChronicleMap;
+import net.openhft.chronicle.map.ChronicleMapBuilder;
+
+public class ChronicleMapCacheImpl<K, V> extends AbstractLoadingCache<K, V>
+    implements PersistentCache {
+
+  private final ChronicleMapCacheConfig config;
+  private final CacheLoader<K, V> loader;
+  private final ChronicleMap<K, TimedValue<V>> store;
+  private final LongAdder hitCount = new LongAdder();
+  private final LongAdder missCount = new LongAdder();
+  private final LongAdder loadSuccessCount = new LongAdder();
+  private final LongAdder loadExceptionCount = new LongAdder();
+  private final LongAdder totalLoadTime = new LongAdder();
+  private final LongAdder evictionCount = new LongAdder();
+
+  @SuppressWarnings("unchecked")
+  ChronicleMapCacheImpl(
+      PersistentCacheDef<K, V> def, ChronicleMapCacheConfig config, CacheLoader<K, V> loader)
+      throws IOException {
+    this.config = config;
+    this.loader = loader;
+
+    final Class<K> keyClass = (Class<K>) def.keyType().getRawType();
+    final Class<TimedValue<V>> valueWrapperClass = (Class<TimedValue<V>>) (Class) TimedValue.class;
+
+    final ChronicleMapBuilder<K, TimedValue<V>> mapBuilder =
+        ChronicleMap.of(keyClass, valueWrapperClass).name(def.name());
+
+    // Chronicle-map does not allow to custom-serialize boxed primitives
+    // such as Boolean, Integer, for which size is statically determined.
+    // This means that even though a custom serializer was provided for a primitive
+    // it cannot be used.
+    // TODO: Should we log.warn when this is the case?
+    if (!mapBuilder.constantlySizedKeys()) {
+      mapBuilder.averageKeySize(config.getAverageKeySize());
+      mapBuilder.keyMarshaller(new ChronicleMapMarshallerAdapter<>(def.keySerializer()));
+    }
+
+    mapBuilder.averageValueSize(config.getAverageValueSize());
+    mapBuilder.valueMarshaller(new TimedValueMarshaller<>(def.valueSerializer()));
+
+    // TODO: ChronicleMap must have "entries" configured, however cache definition
+    //  has already the concept of diskLimit. How to reconcile the two when both
+    //  are defined?
+    //  Should we honour diskLimit, by computing entries as a function of (avgKeySize +
+    // avgValueSize)
+    mapBuilder.entries(config.getMaxEntries());
+
+    if (config.getPersistedFile() == null || config.getDiskLimit() < 0) {
+      store = mapBuilder.create();
+    } else {
+      store = mapBuilder.createOrRecoverPersistedTo(config.getPersistedFile());
+    }
+  }
+
+  public ChronicleMapCacheConfig getConfig() {
+    return config;
+  }
+
+  @Override
+  public V getIfPresent(Object objKey) {
+    if (store.containsKey(objKey)) {
+      TimedValue<V> vTimedValue = store.get(objKey);
+      if (!expired(vTimedValue.getCreated())) {
+        hitCount.increment();
+        return vTimedValue.getValue();
+      } else {
+        invalidate(objKey);
+      }
+    }
+    missCount.increment();
+    return null;
+  }
+
+  @Override
+  public V get(K key) throws ExecutionException {
+    if (store.containsKey(key)) {
+      TimedValue<V> vTimedValue = store.get(key);
+      if (!needsRefresh(vTimedValue.getCreated())) {
+        hitCount.increment();
+        return vTimedValue.getValue();
+      }
+    }
+    missCount.increment();
+    if (loader != null) {
+      V v = null;
+      try {
+        long start = System.nanoTime();
+        v = loader.load(key);
+        totalLoadTime.add(System.nanoTime() - start);
+        loadSuccessCount.increment();
+      } catch (Exception e) {
+        loadExceptionCount.increment();
+        throw new ExecutionException(String.format("Could not load value %s", key), e);
+      }
+      put(key, v);
+      return v;
+    }
+
+    loadExceptionCount.increment();
+    throw new UnsupportedOperationException(
+        String.format("Could not load value for %s without any loader", key));
+  }
+
+  @Override
+  public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
+    if (store.containsKey(key)) {
+      TimedValue<V> vTimedValue = store.get(key);
+      if (!needsRefresh(vTimedValue.getCreated())) {
+        hitCount.increment();
+        return vTimedValue.getValue();
+      }
+    }
+    missCount.increment();
+    V v = null;
+    try {
+      long start = System.nanoTime();
+      v = valueLoader.call();
+      totalLoadTime.add(System.nanoTime() - start);
+      loadSuccessCount.increment();
+    } catch (Exception e) {
+      loadExceptionCount.increment();
+      throw new ExecutionException(String.format("Could not load key %s", key), e);
+    }
+    put(key, v);
+    return v;
+  }
+
+  @Override
+  public void put(K key, V val) {
+    TimedValue<V> wrapped = new TimedValue<>(val);
+    store.put(key, wrapped);
+  }
+
+  public void prune() {
+    store.forEachEntry(
+        c -> {
+          if (expired(c.value().get().getCreated())) {
+            c.context().remove(c);
+          }
+        });
+  }
+
+  private boolean expired(long created) {
+    Duration expireAfterWrite = config.getExpireAfterWrite();
+    Duration age = Duration.between(Instant.ofEpochMilli(created), TimeUtil.now());
+    return !expireAfterWrite.isZero() && age.compareTo(expireAfterWrite) > 0;
+  }
+
+  private boolean needsRefresh(long created) {
+    final Duration refreshAfterWrite = config.getRefreshAfterWrite();
+    Duration age = Duration.between(Instant.ofEpochMilli(created), TimeUtil.now());
+    return !refreshAfterWrite.isZero() && age.compareTo(refreshAfterWrite) > 0;
+  }
+
+  @Override
+  public void invalidate(Object key) {
+    store.remove(key);
+  }
+
+  @Override
+  public void invalidateAll() {
+    store.clear();
+  }
+
+  @Override
+  public long size() {
+    return store.size();
+  }
+
+  @Override
+  public CacheStats stats() {
+    return new CacheStats(
+        hitCount.longValue(),
+        missCount.longValue(),
+        loadSuccessCount.longValue(),
+        loadExceptionCount.longValue(),
+        totalLoadTime.longValue(),
+        evictionCount.longValue());
+  }
+
+  @Override
+  public DiskStats diskStats() {
+    return new DiskStats(
+        size(), config.getPersistedFile().length(), hitCount.longValue(), missCount.longValue());
+  }
+
+  public void close() {
+    store.close();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheModule.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheModule.java
new file mode 100644
index 0000000..99fe5c1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheModule.java
@@ -0,0 +1,30 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.gerrit.lifecycle.LifecycleModule;
+import com.google.gerrit.server.ModuleImpl;
+import com.google.gerrit.server.cache.CacheModule;
+import com.google.gerrit.server.cache.PersistentCacheFactory;
+
+@ModuleImpl(name = CacheModule.PERSISTENT_MODULE)
+public class ChronicleMapCacheModule extends LifecycleModule {
+
+  @Override
+  protected void configure() {
+    factory(ChronicleMapCacheConfig.Factory.class);
+    bind(PersistentCacheFactory.class).to(ChronicleMapCacheFactory.class);
+    listener().to(ChronicleMapCacheFactory.class);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapter.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapter.java
new file mode 100644
index 0000000..0c60dca
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapter.java
@@ -0,0 +1,51 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.gerrit.server.cache.serialize.CacheSerializer;
+import net.openhft.chronicle.bytes.Bytes;
+import net.openhft.chronicle.core.util.ReadResolvable;
+import net.openhft.chronicle.hash.serialization.BytesReader;
+import net.openhft.chronicle.hash.serialization.BytesWriter;
+
+public class ChronicleMapMarshallerAdapter<T>
+    implements BytesWriter<T>, BytesReader<T>, ReadResolvable<ChronicleMapMarshallerAdapter<T>> {
+
+  private final CacheSerializer<T> cacheSerializer;
+
+  ChronicleMapMarshallerAdapter(CacheSerializer<T> cacheSerializer) {
+    this.cacheSerializer = cacheSerializer;
+  }
+
+  @Override
+  public ChronicleMapMarshallerAdapter<T> readResolve() {
+    return new ChronicleMapMarshallerAdapter<>(cacheSerializer);
+  }
+
+  @Override
+  public T read(Bytes in, T using) {
+    int serializedLength = (int) in.readUnsignedInt();
+    byte[] serialized = new byte[serializedLength];
+    in.read(serialized, 0, serializedLength);
+    using = cacheSerializer.deserialize(serialized);
+    return using;
+  }
+
+  @Override
+  public void write(Bytes out, T toWrite) {
+    final byte[] serialized = cacheSerializer.serialize(toWrite);
+    out.writeUnsignedInt(serialized.length);
+    out.write(serialized);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValue.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValue.java
new file mode 100644
index 0000000..6bb53bc
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValue.java
@@ -0,0 +1,53 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.common.base.Objects;
+
+public class TimedValue<V> {
+
+  private final V value;
+  private final long created;
+
+  TimedValue(V value) {
+    this.created = System.currentTimeMillis();
+    this.value = value;
+  }
+
+  protected TimedValue(V value, long created) {
+    this.created = created;
+    this.value = value;
+  }
+
+  public long getCreated() {
+    return created;
+  }
+
+  public V getValue() {
+    return value;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (!(o instanceof TimedValue)) return false;
+    TimedValue<?> that = (TimedValue<?>) o;
+    return created == that.created && Objects.equal(value, that.value);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hashCode(value, created);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshaller.java b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshaller.java
new file mode 100644
index 0000000..60897bf
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshaller.java
@@ -0,0 +1,89 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import com.google.gerrit.server.cache.serialize.CacheSerializer;
+import java.nio.ByteBuffer;
+import net.openhft.chronicle.bytes.Bytes;
+import net.openhft.chronicle.core.util.ReadResolvable;
+import net.openhft.chronicle.hash.serialization.BytesReader;
+import net.openhft.chronicle.hash.serialization.BytesWriter;
+
+public class TimedValueMarshaller<V>
+    implements BytesWriter<TimedValue<V>>,
+        BytesReader<TimedValue<V>>,
+        ReadResolvable<TimedValueMarshaller<V>> {
+
+  private final CacheSerializer<V> serializer;
+
+  TimedValueMarshaller(CacheSerializer<V> serializer) {
+    this.serializer = serializer;
+  }
+
+  @Override
+  public TimedValueMarshaller<V> readResolve() {
+    return new TimedValueMarshaller<>(serializer);
+  }
+
+  @Override
+  public TimedValue<V> read(Bytes in, TimedValue<V> using) {
+    long initialPosition = in.readPosition();
+
+    // Deserialize the creation timestamp (first 8 bytes)
+    byte[] serializedLong = new byte[Long.BYTES];
+    in.read(serializedLong, 0, Long.BYTES);
+    ByteBuffer buffer = ByteBuffer.wrap(serializedLong);
+    long created = buffer.getLong(0);
+    in.readPosition(initialPosition + Long.BYTES);
+
+    // Deserialize the length of the serialized value (second 8 bytes)
+    byte[] serializedInt = new byte[Integer.BYTES];
+    in.read(serializedInt, 0, Integer.BYTES);
+    ByteBuffer buffer2 = ByteBuffer.wrap(serializedInt);
+    int vLength = buffer2.getInt(0);
+    in.readPosition(initialPosition + Long.BYTES + Integer.BYTES);
+
+    // Deserialize object V (remaining bytes)
+    byte[] serializedV = new byte[vLength];
+    in.read(serializedV, 0, vLength);
+    V v = serializer.deserialize(serializedV);
+
+    using = new TimedValue<>(v, created);
+
+    return using;
+  }
+
+  @Override
+  public void write(Bytes out, TimedValue<V> toWrite) {
+    byte[] serialized = serializer.serialize(toWrite.getValue());
+
+    // Serialize as follows:
+    // created | length of serialized V | serialized value V
+    // 8 bytes |       4 bytes          | serialized_length bytes
+
+    int capacity = Long.BYTES + Integer.BYTES + serialized.length;
+    ByteBuffer buffer = ByteBuffer.allocate(capacity);
+
+    long timestamp = toWrite.getCreated();
+    buffer.putLong(0, timestamp);
+
+    buffer.position(Long.BYTES);
+    buffer.putInt(serialized.length);
+
+    buffer.position(Long.BYTES + Integer.BYTES);
+    buffer.put(serialized);
+
+    out.write(buffer.array());
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfigTest.java b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfigTest.java
new file mode 100644
index 0000000..5f003d7
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheConfigTest.java
@@ -0,0 +1,173 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.googlesource.gerrit.modules.cache.chroniclemap.ChronicleMapCacheConfig.DEFAULT_AVG_KEY_SIZE;
+import static com.googlesource.gerrit.modules.cache.chroniclemap.ChronicleMapCacheConfig.DEFAULT_AVG_VALUE_SIZE;
+import static com.googlesource.gerrit.modules.cache.chroniclemap.ChronicleMapCacheConfig.DEFAULT_MAX_ENTRIES;
+
+import com.google.gerrit.server.config.SitePaths;
+import java.nio.file.Files;
+import java.time.Duration;
+import org.eclipse.jgit.lib.StoredConfig;
+import org.eclipse.jgit.storage.file.FileBasedConfig;
+import org.eclipse.jgit.util.FS;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class ChronicleMapCacheConfigTest {
+
+  private final String cacheName = "foobar-cache";
+  private final String cacheKey = "foobar-cache-key";
+  private final long definitionDiskLimit = 100;
+  private final Duration expireAfterWrite = Duration.ofSeconds(10_000);
+  private final Duration refreshAfterWrite = Duration.ofSeconds(20_000);
+
+  @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
+  private SitePaths sitePaths;
+  private StoredConfig gerritConfig;
+
+  @Before
+  public void setUp() throws Exception {
+    sitePaths = new SitePaths(temporaryFolder.newFolder().toPath());
+    Files.createDirectories(sitePaths.etc_dir);
+
+    gerritConfig =
+        new FileBasedConfig(
+            sitePaths.resolve("etc").resolve("gerrit.config").toFile(), FS.DETECTED);
+    gerritConfig.load();
+  }
+
+  @Test
+  public void shouldProvidePersistedFileWhenCacheDirIsConfigured() throws Exception {
+    final String directory = "cache-dir";
+    gerritConfig.setString("cache", null, "directory", directory);
+    gerritConfig.save();
+
+    assertThat(
+            configUnderTest(gerritConfig)
+                .getPersistedFile()
+                .toPath()
+                .getParent()
+                .toRealPath()
+                .toString())
+        .isEqualTo(sitePaths.resolve(directory).toRealPath().toString());
+  }
+
+  @Test
+  public void shouldNotProvidePersistedFileWhenCacheDirIsNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getPersistedFile()).isNull();
+  }
+
+  @Test
+  public void shouldProvideConfiguredDiskLimitWhenDefined() throws Exception {
+    long configuredDiskLimit = 50;
+    gerritConfig.setLong("cache", cacheKey, "diskLimit", configuredDiskLimit);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getDiskLimit()).isEqualTo(configuredDiskLimit);
+  }
+
+  @Test
+  public void shouldProvideDefinitionDiskLimitWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getDiskLimit()).isEqualTo(definitionDiskLimit);
+  }
+
+  @Test
+  public void shouldProvideConfiguredMaxEntriesWhenDefined() throws Exception {
+    long maxEntries = 10;
+    gerritConfig.setLong("cache", cacheKey, "maxEntries", maxEntries);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getMaxEntries()).isEqualTo(maxEntries);
+  }
+
+  @Test
+  public void shouldProvideDefaultMaxEntriesWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getMaxEntries()).isEqualTo(DEFAULT_MAX_ENTRIES);
+  }
+
+  @Test
+  public void shouldProvideAverageKeySizeWhenConfigured() throws Exception {
+    long averageKeySize = 5;
+    gerritConfig.setLong("cache", cacheKey, "avgKeySize", averageKeySize);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getAverageKeySize()).isEqualTo(averageKeySize);
+  }
+
+  @Test
+  public void shouldProvideDefaultAverageKeySizeWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getAverageKeySize()).isEqualTo(DEFAULT_AVG_KEY_SIZE);
+  }
+
+  @Test
+  public void shouldProvideAverageValueSizeWhenConfigured() throws Exception {
+    long averageValueSize = 6;
+    gerritConfig.setLong("cache", cacheKey, "avgValueSize", averageValueSize);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getAverageValueSize()).isEqualTo(averageValueSize);
+  }
+
+  @Test
+  public void shouldProvideDefaultAverageValueSizeWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getAverageValueSize())
+        .isEqualTo(DEFAULT_AVG_VALUE_SIZE);
+  }
+
+  @Test
+  public void shouldProvideExpireAfterWriteWhenMaxAgeIsConfgured() throws Exception {
+    String maxAge = "3 minutes";
+    gerritConfig.setString("cache", cacheKey, "maxAge", maxAge);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getExpireAfterWrite())
+        .isEqualTo(Duration.ofSeconds(180));
+  }
+
+  @Test
+  public void shouldProvideDefinitionExpireAfterWriteWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getExpireAfterWrite()).isEqualTo(expireAfterWrite);
+  }
+
+  @Test
+  public void shouldProvideRefreshAfterWriteWhenConfigured() throws Exception {
+    String refreshAfterWrite = "6 minutes";
+    gerritConfig.setString("cache", cacheKey, "refreshAfterWrite", refreshAfterWrite);
+    gerritConfig.save();
+
+    assertThat(configUnderTest(gerritConfig).getRefreshAfterWrite())
+        .isEqualTo(Duration.ofSeconds(360));
+  }
+
+  @Test
+  public void shouldProvideDefinitionRefreshAfterWriteWhenNotConfigured() {
+    assertThat(configUnderTest(gerritConfig).getRefreshAfterWrite()).isEqualTo(refreshAfterWrite);
+  }
+
+  private ChronicleMapCacheConfig configUnderTest(StoredConfig gerritConfig) {
+    return new ChronicleMapCacheConfig(
+        gerritConfig,
+        sitePaths,
+        cacheName,
+        cacheKey,
+        definitionDiskLimit,
+        expireAfterWrite,
+        refreshAfterWrite);
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheIT.java b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheIT.java
new file mode 100644
index 0000000..69f0845
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheIT.java
@@ -0,0 +1,60 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
+
+import com.google.common.truth.Truth8;
+import com.google.gerrit.acceptance.AbstractDaemonTest;
+import com.google.gerrit.acceptance.RestResponse;
+import com.google.gerrit.entities.Project;
+import com.google.gerrit.extensions.api.accounts.AccountInput;
+import com.google.gerrit.server.cache.PersistentCacheFactory;
+import com.google.inject.Inject;
+import org.junit.Test;
+
+public class ChronicleMapCacheIT extends AbstractDaemonTest {
+
+  @Inject PersistentCacheFactory persistentCacheFactory;
+
+  @Override
+  public com.google.inject.Module createModule() {
+    return new ChronicleMapCacheModule();
+  }
+
+  @Test
+  public void shouldBeAbleToInstallChronicleMapCacheFactory() {
+    assertThat(persistentCacheFactory).isInstanceOf(ChronicleMapCacheFactory.class);
+  }
+
+  @Test
+  public void shouldCacheNewProject() throws Exception {
+    String newProjectName = name("newProject");
+    RestResponse r = adminRestSession.put("/projects/" + newProjectName);
+
+    Truth8.assertThat(projectCache.get(Project.nameKey(newProjectName))).isPresent();
+  }
+
+  @Test
+  public void shouldCacheNewUser() throws Exception {
+    AccountInput input = new AccountInput();
+    input.username = "foo";
+
+    assertThat(accountCache.getByUsername(input.username)).isEmpty();
+    adminRestSession.put("/accounts/" + input.username, input);
+
+    assertThat(accountCache.getByUsername(input.username)).isPresent();
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheTest.java b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheTest.java
new file mode 100644
index 0000000..43205c0
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapCacheTest.java
@@ -0,0 +1,336 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.gerrit.testing.GerritJUnit.assertThrows;
+
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.Weigher;
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.server.cache.PersistentCacheDef;
+import com.google.gerrit.server.cache.serialize.CacheSerializer;
+import com.google.gerrit.server.cache.serialize.StringCacheSerializer;
+import com.google.gerrit.server.config.SitePaths;
+import com.google.inject.TypeLiteral;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.time.Duration;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import org.eclipse.jgit.lib.StoredConfig;
+import org.eclipse.jgit.storage.file.FileBasedConfig;
+import org.eclipse.jgit.util.FS;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class ChronicleMapCacheTest {
+
+  @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
+  private SitePaths sitePaths;
+  private StoredConfig gerritConfig;
+
+  @Before
+  public void setUp() throws Exception {
+    sitePaths = new SitePaths(temporaryFolder.newFolder().toPath());
+    Files.createDirectories(sitePaths.etc_dir);
+
+    gerritConfig =
+        new FileBasedConfig(
+            sitePaths.resolve("etc").resolve("gerrit.config").toFile(), FS.DETECTED);
+    gerritConfig.load();
+  }
+
+  @Test
+  public void getIfPresentShouldReturnNullWhenThereisNoCachedValue() throws Exception {
+    assertThat(newCacheWithLoader(null).getIfPresent("foo")).isNull();
+  }
+
+  @Test
+  public void getWithLoaderShouldPopulateTheCache() throws Exception {
+    String cachedValue = UUID.randomUUID().toString();
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    assertThat(cache.get("foo", () -> cachedValue)).isEqualTo(cachedValue);
+    assertThat(cache.get("foo")).isEqualTo(cachedValue);
+  }
+
+  @Test
+  public void getShouldRetrieveTheValueViaTheLoader() throws Exception {
+    String cachedValue = UUID.randomUUID().toString();
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader(cachedValue);
+
+    assertThat(cache.get("foo")).isEqualTo(cachedValue);
+  }
+
+  @Test
+  public void getShoudThrowWhenNoLoaderHasBeenProvided() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithoutLoader();
+
+    UnsupportedOperationException thrown =
+        assertThrows(UnsupportedOperationException.class, () -> cache.get("foo"));
+    assertThat(thrown).hasMessageThat().contains("Could not load value");
+  }
+
+  @Test
+  public void shouldIncreaseMissCountWhenValueIsNotInCache() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    cache.getIfPresent("foo");
+    assertThat(cache.stats().hitCount()).isEqualTo(0);
+    assertThat(cache.stats().missCount()).isEqualTo(1);
+  }
+
+  @Test
+  public void shouldIncreaseHitCountWhenValueIsInCache() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    cache.put("foo", "bar");
+    cache.getIfPresent("foo");
+
+    assertThat(cache.stats().hitCount()).isEqualTo(1);
+    assertThat(cache.stats().missCount()).isEqualTo(0);
+  }
+
+  @Test
+  public void shouldIncreaseLoadSuccessCountWhenValueIsLoadedFromCacheDefinitionLoader()
+      throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    cache.get("foo");
+
+    assertThat(cache.stats().loadSuccessCount()).isEqualTo(1);
+    assertThat(cache.stats().loadExceptionCount()).isEqualTo(0);
+  }
+
+  @Test
+  public void valueShouldBeCachedAfterPut() throws Exception {
+    String cachedValue = UUID.randomUUID().toString();
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    cache.put("foo", cachedValue);
+    assertThat(cache.get("foo")).isEqualTo(cachedValue);
+  }
+
+  @Test
+  public void shouldIncreaseLoadExceptionCountWhenNoLoaderIsAvailable() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithoutLoader();
+
+    assertThrows(UnsupportedOperationException.class, () -> cache.get("foo"));
+
+    assertThat(cache.stats().loadExceptionCount()).isEqualTo(1);
+    assertThat(cache.stats().loadSuccessCount()).isEqualTo(0);
+  }
+
+  @Test
+  public void shouldIncreaseLoadExceptionCountWhenLoaderThrows() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader();
+
+    assertThrows(
+        ExecutionException.class,
+        () ->
+            cache.get(
+                "foo",
+                () -> {
+                  throw new Exception("Boom!");
+                }));
+
+    assertThat(cache.stats().loadExceptionCount()).isEqualTo(1);
+    assertThat(cache.stats().loadSuccessCount()).isEqualTo(0);
+  }
+
+  @Test
+  public void shouldIncreaseLoadSuccessCountWhenValueIsLoadedFromCallableLoader() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader(null);
+
+    cache.get("foo", () -> "some-value");
+
+    assertThat(cache.stats().loadSuccessCount()).isEqualTo(1);
+    assertThat(cache.stats().loadExceptionCount()).isEqualTo(0);
+  }
+
+  @Test
+  public void getIfPresentShouldReturnNullWhenValueIsExpired() throws Exception {
+    ChronicleMapCacheImpl<String, String> cache = newCache(true, null, Duration.ofSeconds(1), null);
+    cache.put("foo", "some-stale-value");
+    Thread.sleep(1000); // Allow cache entry to expire
+    assertThat(cache.getIfPresent("foo")).isNull();
+  }
+
+  @Test
+  public void getShouldRefreshValueWhenExpired() throws Exception {
+    String newCachedValue = UUID.randomUUID().toString();
+    ChronicleMapCacheImpl<String, String> cache =
+        newCache(true, newCachedValue, null, Duration.ofSeconds(1));
+    cache.put("foo", "some-stale-value");
+    Thread.sleep(1000); // Allow cache to be flagged as needing refresh
+    assertThat(cache.get("foo")).isEqualTo(newCachedValue);
+  }
+
+  @Test
+  public void shouldPruneExpiredValues() throws Exception {
+    ChronicleMapCacheImpl<String, String> cache = newCache(true, null, Duration.ofSeconds(1), null);
+    cache.put("foo1", "some-stale-value1");
+    cache.put("foo2", "some-stale-value1");
+    Thread.sleep(1000); // Allow cache entries to expire
+    cache.put("foo3", "some-fresh-value3");
+    cache.prune();
+
+    assertThat(cache.size()).isEqualTo(1);
+    assertThat(cache.get("foo3")).isEqualTo("some-fresh-value3");
+  }
+
+  @Test
+  public void shouldLoadNewValueAfterBeingInvalidated() throws Exception {
+    String cachedValue = UUID.randomUUID().toString();
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithLoader(cachedValue);
+    cache.put("foo", "old-value");
+    cache.invalidate("foo");
+
+    assertThat(cache.size()).isEqualTo(0);
+    assertThat(cache.get("foo")).isEqualTo(cachedValue);
+  }
+
+  @Test
+  public void shouldClearAllEntriesWhenInvalidateAll() throws Exception {
+    final ChronicleMapCacheImpl<String, String> cache = newCacheWithoutLoader();
+    cache.put("foo1", "some-value");
+    cache.put("foo2", "some-value");
+
+    cache.invalidateAll();
+
+    assertThat(cache.size()).isEqualTo(0);
+  }
+
+  private ChronicleMapCacheImpl<String, String> newCache(
+      Boolean withLoader,
+      @Nullable String cachedValue,
+      @Nullable Duration expireAfterWrite,
+      @Nullable Duration refreshAfterWrite)
+      throws IOException {
+    TestPersistentCacheDef cacheDef = new TestPersistentCacheDef(cachedValue);
+
+    ChronicleMapCacheConfig config =
+        new ChronicleMapCacheConfig(
+            gerritConfig,
+            sitePaths,
+            cacheDef.name(),
+            cacheDef.configKey(),
+            cacheDef.diskLimit(),
+            expireAfterWrite != null ? expireAfterWrite : Duration.ZERO,
+            refreshAfterWrite != null ? refreshAfterWrite : Duration.ZERO);
+
+    return new ChronicleMapCacheImpl<>(cacheDef, config, withLoader ? cacheDef.loader() : null);
+  }
+
+  private ChronicleMapCacheImpl<String, String> newCacheWithLoader(@Nullable String cachedValue)
+      throws IOException {
+    return newCache(true, cachedValue, null, null);
+  }
+
+  private ChronicleMapCacheImpl<String, String> newCacheWithLoader() throws IOException {
+    return newCache(true, null, null, null);
+  }
+
+  private ChronicleMapCacheImpl<String, String> newCacheWithoutLoader() throws IOException {
+    return newCache(false, null, null, null);
+  }
+
+  public static class TestPersistentCacheDef implements PersistentCacheDef<String, String> {
+
+    private final String loadedValue;
+
+    TestPersistentCacheDef(@Nullable String loadedValue) {
+
+      this.loadedValue = loadedValue;
+    }
+
+    @Override
+    public long diskLimit() {
+      return 0;
+    }
+
+    @Override
+    public int version() {
+      return 0;
+    }
+
+    @Override
+    public CacheSerializer<String> keySerializer() {
+      return StringCacheSerializer.INSTANCE;
+    }
+
+    @Override
+    public CacheSerializer<String> valueSerializer() {
+      return StringCacheSerializer.INSTANCE;
+    }
+
+    @Override
+    public String name() {
+      return "chronicle-map-test-cache";
+    }
+
+    @Override
+    public String configKey() {
+      return name();
+    }
+
+    @Override
+    public TypeLiteral<String> keyType() {
+      return new TypeLiteral<String>() {};
+    }
+
+    @Override
+    public TypeLiteral<String> valueType() {
+      return new TypeLiteral<String>() {};
+    }
+
+    @Override
+    public long maximumWeight() {
+      return 0;
+    }
+
+    @Override
+    public Duration expireAfterWrite() {
+      return Duration.ZERO;
+    }
+
+    @Override
+    public Duration expireFromMemoryAfterAccess() {
+      return Duration.ZERO;
+    }
+
+    @Override
+    public Duration refreshAfterWrite() {
+      return Duration.ZERO;
+    }
+
+    @Override
+    public Weigher<String, String> weigher() {
+      return (s, s2) -> 0;
+    }
+
+    @Override
+    public CacheLoader<String, String> loader() {
+      return new CacheLoader<String, String>() {
+        @Override
+        public String load(String s) {
+          return loadedValue != null ? loadedValue : UUID.randomUUID().toString();
+        }
+      };
+    }
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapterTest.java b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapterTest.java
new file mode 100644
index 0000000..09f7f17
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/ChronicleMapMarshallerAdapterTest.java
@@ -0,0 +1,53 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// limitations under the License.
+// See the License for the specific language governing permissions and
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.gerrit.server.cache.serialize.ObjectIdCacheSerializer;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import net.openhft.chronicle.bytes.Bytes;
+import org.eclipse.jgit.lib.ObjectId;
+import org.junit.Test;
+
+public class ChronicleMapMarshallerAdapterTest {
+
+  @Test
+  public void shouldDeserializeToTheSameObject() {
+    ObjectId id = ObjectId.fromString("aabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
+    byte[] serializedId = ObjectIdCacheSerializer.INSTANCE.serialize(id);
+    ByteBuffer serializedIdWithLen = ByteBuffer.allocate(serializedId.length + 4);
+    serializedIdWithLen.order(ByteOrder.LITTLE_ENDIAN);
+    serializedIdWithLen.putInt(serializedId.length);
+    serializedIdWithLen.put(serializedId);
+
+    ChronicleMapMarshallerAdapter<ObjectId> marshaller =
+        new ChronicleMapMarshallerAdapter<>(ObjectIdCacheSerializer.INSTANCE);
+    ObjectId out = marshaller.read(Bytes.allocateDirect(serializedIdWithLen.array()), null);
+
+    assertThat(id).isEqualTo(out);
+  }
+
+  @Test
+  public void shouldSerializeToTheSameObject() {
+    ObjectId id = ObjectId.fromString("aabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
+    ChronicleMapMarshallerAdapter<ObjectId> marshaller =
+        new ChronicleMapMarshallerAdapter<>(ObjectIdCacheSerializer.INSTANCE);
+
+    Bytes<ByteBuffer> out = Bytes.elasticByteBuffer();
+    marshaller.write(out, id);
+    assertThat(marshaller.read(out, null)).isEqualTo(id);
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshallerTest.java b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshallerTest.java
new file mode 100644
index 0000000..62c1d44
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/modules/cache/chroniclemap/TimedValueMarshallerTest.java
@@ -0,0 +1,40 @@
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+package com.googlesource.gerrit.modules.cache.chroniclemap;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.gerrit.server.cache.serialize.ObjectIdCacheSerializer;
+import java.nio.ByteBuffer;
+import net.openhft.chronicle.bytes.Bytes;
+import org.eclipse.jgit.lib.ObjectId;
+import org.junit.Test;
+
+public class TimedValueMarshallerTest {
+
+  @Test
+  public void shouldSerializeAndDeserializeBack() {
+    ObjectId id = ObjectId.fromString("1234567890123456789012345678901234567890");
+    long timestamp = 1600329018L;
+    TimedValueMarshaller<ObjectId> marshaller =
+        new TimedValueMarshaller<>(ObjectIdCacheSerializer.INSTANCE);
+
+    final TimedValue<ObjectId> wrapped = new TimedValue<>(id, timestamp);
+
+    Bytes<ByteBuffer> out = Bytes.elasticByteBuffer();
+    marshaller.write(out, wrapped);
+    final TimedValue<ObjectId> actual = marshaller.read(out, null);
+    assertThat(actual).isEqualTo(wrapped);
+  }
+}