{"id":15343635,"url":"https://github.com/kezhenxu94/cache-lite","last_synced_at":"2025-11-07T02:04:01.730Z","repository":{"id":43862527,"uuid":"135662994","full_name":"kezhenxu94/cache-lite","owner":"kezhenxu94","description":"An extremely lite-weight cache framework in Kotlin, demonstrating how cache works.","archived":false,"fork":false,"pushed_at":"2021-04-27T04:48:55.000Z","size":189,"stargazers_count":143,"open_issues_count":1,"forks_count":11,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-10T15:48:40.946Z","etag":null,"topics":["cache","cache-lite","kotlin","tutorial","tutorial-code","tutorial-sourcecode","tutorials"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kezhenxu94.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-06-01T03:27:30.000Z","updated_at":"2025-04-01T16:33:00.000Z","dependencies_parsed_at":"2022-07-08T05:59:00.493Z","dependency_job_id":null,"html_url":"https://github.com/kezhenxu94/cache-lite","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kezhenxu94%2Fcache-lite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kezhenxu94%2Fcache-lite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kezhenxu94%2Fcache-lite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kezhenxu94%2Fcache-lite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kezhenxu94","download_url":"https://codeload.github.com/kezhenxu94/cache-lite/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248943456,"owners_count":21186958,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","cache-lite","kotlin","tutorial","tutorial-code","tutorial-sourcecode","tutorials"],"created_at":"2024-10-01T10:48:00.133Z","updated_at":"2025-11-07T02:03:56.706Z","avatar_url":"https://github.com/kezhenxu94.png","language":null,"funding_links":[],"categories":["Tutorials"],"sub_categories":[],"readme":"Cache-Lite - An extremely light-weight cache framework for Kotlin\n=================================================================\n\n[![Build](https://github.com/kezhenxu94/cache-lite/workflows/Build/badge.svg?branch=master)](https://github.com/kezhenxu94/cache-lite/actions?query=branch%3Amaster+event%3Apush+workflow%3A%22Build%22)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/ba9c9aa2b9484f44ad1406763094bb63)](https://app.codacy.com/manual/kezhenxu94/cache-lite?utm_source=github.com\u0026utm_medium=referral\u0026utm_content=kezhenxu94/cache-lite\u0026utm_campaign=Badge_Grade_Dashboard)\n[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%20v2.0-blue.svg)](https://apache.org)\n[![Kotlin Version](https://img.shields.io/badge/Kotlin-1.3.71-blue.svg)](https://kotlinlang.org)\n[![Maven Central](https://img.shields.io/maven-central/v/io.github.kezhenxu94/cache-lite)](https://mvnrepository.com/artifact/io.github.kezhenxu94/cache-lite)\n[![codecov](https://codecov.io/gh/kezhenxu94/cache-lite/branch/master/graph/badge.svg)](https://codecov.io/gh/kezhenxu94/cache-lite)\n\nThe Cache-Lite is an extremely light-weight cache framework implemented in Kotlin, it is for study case.\n\nYou can check out the source code to learn how caching works and learn how to implement a simple cache framework by yourself.\n\n## Usage\n\nAlthough this is a simple project for study case, it's well tested and you can still use it in your project if you found it fits your use case.\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003eio.github.kezhenxu94\u003c/groupId\u003e\n  \u003cartifactId\u003ecache-lite\u003c/artifactId\u003e\n  \u003cversion\u003e${cache-lite.version}\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n## Background\n\nCaching is a critical technology in many high performance scalable applications. There are many choices in caching framework, including [Ehcache](http://www.ehcache.org/), [Memcache](https://memcached.org/), [cache2k](https://cache2k.org/) etc. But today we are going to build one on our own, to learn what cache really does. Let's get started.\n\n## Naive Version\n\nA cache is typically a key-value store, and in Kotlin/Java there is exactly a class representing this kind of data structure: `Map`. There are chances that we have already leveraged this class to do some caching tasks. So the very first thought to build a caching framework is simply using the class `java.util.Map`.\n\n```kotlin\nval cache = HashMap\u003cAny, Any\u003e()\ncache[\"key\"] = \"Frequently used value taken from database\"\nval v = cache[\"key\"]\nprintln(v)\ncache.remove(\"key\")\n```\n\nQuite simple, isn't it? But according to the programming principle, \"Program to Interface, not Implementation\", we should not couple our caching framework to the specific implementation, which is `java.util.Map` here. You may argue that `java.util.Map` **is an interface, not an implementation**. True, but not applicable here. Here we are talking about a caching system, which means that, for end users, **caching is an interface and `java.util.Map` is an implementation that they don't care**. We have to define an interface that only describes what a cache does.\n\n## Defining `Cache` Interface\n\nThere are some basic operations on a cache, you may want to `put` a value into it, `get` a value by `key` from it, `remove` a value by `key` from it, `clear` it and know what's the `size` of it. After saying the sentence, our interface `Cache` is almost done.\n\n```kotlin\ninterface Cache {\n  val size: Int\n\n  operator fun set(key: Any, value: Any)\n\n  operator fun get(key: Any): Any?\n\n  fun remove(key: Any): Any?\n\n  fun clear()\n}\n```\n\nHere is one thing different from what we just said, the method `set`. The reason why we name it `set` is that we want to use operator `[]` to put a value by key into the cache. By using `operator function set`, we are able to put a value into cache like this: `cache[\"key\"] = \"value\"`, instead of `cache.put(\"key\", \"value\")`.\n\n## Cache Forever\n\nOne of the challenges in designing a caching framework is to deal with the expiration of the **cached items**. But for simplicity, we are ignoring this **now** and build our first cache that caches items forever until we remove it manually.\n\nIt is true that we should program to interface not implementation, but when we are **implementing an interface**, we could leverage some other implementations, here we will use `java.util.Map` to implement our first cache, `PerpetualCache`:\n\n```kotlin\nclass PerpetualCache : Cache {\n  private val cache = HashMap\u003cAny, Any\u003e()\n\n  override val size: Int\n    get() = cache.size\n\n  override fun set(key: Any, value: Any) {\n    this.cache[key] = value\n  }\n\n  override fun remove(key: Any) = this.cache.remove(key)\n\n  override fun get(key: Any) = this.cache[key]\n\n  override fun clear() = this.cache.clear()\n}\n```\n\nAll of the methods are **delegated** to `cache`, it is fine because `cache` is `private` so that we can change our implementation without effecting our end users. Now that we have our own cache interface `Cache` and one of  implementations of it, `PerpetualCache`, we want to add more functionalities.\n\n## LRU Cache\n\nBy now our cache will keep all the entries until we remove them manually, it can be very memory-intensive. In many caching scenarios, we assume that **the entries we recently used will be used again soon**, if that is true (mostly it is), we can keep only a certain number of entries that are recently used and remove others, this kind of flush strategy is called **[Least Recently Used](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.\n\nSince we already have `PerpetualCache` and we want to **add responsibilities** to this class, the **[Decorator Pattern](https://en.wikipedia.org/wiki/Decorator_pattern)** is the best choice here.\n\n```kotlin\nclass LRUCache(private val delegate: Cache, private val minimalSize: Int = DEFAULT_SIZE) : Cache by delegate {\n  private val keyMap = object : LinkedHashMap\u003cAny, Any\u003e(minimalSize, .75f, true) {\n    override fun removeEldestEntry(eldest: MutableMap.MutableEntry\u003cAny, Any\u003e): Boolean {\n      val tooManyCachedItems = size \u003e minimalSize\n      if (tooManyCachedItems) eldestKeyToRemove = eldest.key\n      return tooManyCachedItems\n    }\n  }\n\n  private var eldestKeyToRemove: Any? = null\n\n  override fun set(key: Any, value: Any) {\n    delegate[key] = value\n    cycleKeyMap(key)\n  }\n\n  override fun get(key: Any): Any? {\n    keyMap[key]\n    return delegate[key]\n  }\n\n  override fun clear() {\n    keyMap.clear()\n    delegate.clear()\n  }\n\n  private fun cycleKeyMap(key: Any) {\n    keyMap[key] = PRESENT\n    eldestKeyToRemove?.let { delegate.remove(it) }\n    eldestKeyToRemove = null\n  }\n\n  companion object {\n    private const val DEFAULT_SIZE = 100\n    private const val PRESENT = true\n  }\n}\n```\n\nWe only keep `minimalSize` entries at most. Here we leverage the class `java.util.LinkedHashMap` to trace the usage of entries, and `eldestKeyToRemove` is the one to be removed, which is the eldest entry ordered by used frequency. Method `cycleKeyMap` is responsible for removing entries that are too old and less used. Simple and straightforward.\n\n## Expirable Cache\n\nAs we said above, expiration is critical in caching framework because it prevent our cache from growing infinitely. With the experience of `LRUCache` implementation, we know how and when to remove entries, it's time to implement an expirable cache.\n\n```kotlin\nclass ExpirableCache(private val delegate: Cache,\n                     private val flushInterval: Long = TimeUnit.MINUTES.toMillis(1)) : Cache by delegate {\n  private var lastFlushTime = System.nanoTime()\n\n  override val size: Int\n    get() {\n      recycle()\n      return delegate.size\n    }\n\n  override fun remove(key: Any): Any? {\n    recycle()\n    return delegate.remove(key)\n  }\n\n  override fun get(key: Any): Any? {\n    recycle()\n    return delegate[key]\n  }\n\n  private fun recycle() {\n    val shouldRecycle = System.nanoTime() - lastFlushTime \u003e= TimeUnit.MILLISECONDS.toNanos(flushInterval)\n    if (!shouldRecycle) return\n    delegate.clear()\n  }\n}\n```\n\nTo make it simple, by saying expirable, we means that the **cache** is expirable, **not a single entry** in the cache is expirable. However, after knowing how the entire cache is expired, it's easy to implement a cache where entries are expired respectively.\n\nWe are given a `flushInterval`, and we will clear the cache every `flushInterval` milliseconds. It's typically a **scheduled task**, we can use a background thread to do the task, but again, to make it simple, we just `recycle` before every operation in our cache.\n\n## Other Implementations\n\nBesides the three implementations we discussed above, here are several implementations such as `FIFOCache`, `SoftCache` and `WeakCache`, implemented with **[First-in-first-out algorithm](https://en.wikipedia.org/wiki/FIFO_%28computing_and_electronics%29)**, **[Soft Reference](https://en.wikipedia.org/wiki/Soft_reference)**, and **[Weak Reference](https://en.wikipedia.org/wiki/Weak_reference)** respectively.\n\n## None-typed Cache\n\nTo make a cache more flexible, in terms of values it can store, Cache type can be used which is just a type-alias\n\n```kotlin\ntypealias Cache = GenericCache\u003cAny, Any\u003e\n```\n\nYou can check out the source code [here in GitHub](https://github.com/kezhenxu94/cache-lite).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkezhenxu94%2Fcache-lite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkezhenxu94%2Fcache-lite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkezhenxu94%2Fcache-lite/lists"}