A Disk & Memory LRU Cache Library for JVM/Android.
Inspired by Glide's implementation.
Add the dependency to your build.gradle:
dependencies {
// ...
implementation 'io.github.tans5:tlrucache:1.0.0'
// ...
}
Initialization
// Create a pool with maximum size of 1024 bytes
val bytesPool = LruByteArrayPool(1024L)
Obtaining and Releasing Buffers
// Request a 10-byte buffer
val buffer = bytesPool.get(10)
val byteArray = buffer.value
// Use the byte array
// ...
// Return the buffer to the pool
bytesPool.put(buffer)
Cleanup
// Release resources when no longer needed
bytesPool.release()
Initialization
val diskCache = DiskLruCache.open(
directory = baseDir, // Base directory for cache files
appVersion = 1, // App version (used for cache invalidation)
valueCount = 1, // Number of files per entry
maxSize = 5 * 1024L // Maximum cache size (5KB)
)
Writing to Cache
diskCache.edit(key)?.let { editor ->
val file = editor.getFile(0).apply {
if (!exists()) createNewFile()
}
try {
file.outputStream().use { stream ->
// Write data to the file
}
editor.commit() // Persist changes
} catch (e: Throwable) {
editor.abort() // Discard on failure
}
}
Reading from Cache
diskCache.get(key)?.let { snapshot ->
val file = snapshot.getFile(0)
val bytes = file.readBytes()
// Process cached data
}
Closing the Cache
diskCache.close()