Skip to content

Commit

Permalink
使用ConcurrentLinkedHashMap和AtomicLong优化缓存性能
Browse files Browse the repository at this point in the history
  • Loading branch information
ltttttttttttt committed Apr 23, 2024
1 parent 7564c05 commit f589cd4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
1 change: 1 addition & 0 deletions load-the-image/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ java {
dependencies {
implementation(compose.ui)
implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
implementation("com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2")
}

publishing {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package com.lt.load_the_image.cache

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap
import java.util.concurrent.atomic.AtomicLong

/**
* creator: lt 2022/4/8 [email protected]
* effect : Memory cache configuration of network image, cache use LRU
Expand All @@ -25,24 +28,25 @@ open class ImageLruMemoryCache(
private val maxMemorySize: Long = getMemoryWithOnePercent()
) : ImageCache {
//image lru cache
private val cacheMap = LinkedHashMap<String, ByteArray>(35, 1f, true)
private val cacheMap = ConcurrentLinkedHashMap.Builder<String, ByteArray>()
.initialCapacity(35)
.maximumWeightedCapacity(9999)
.build()

//image cache byte size sum
private var cacheSize: Long = 0
private var cacheSize = AtomicLong(0)

@Synchronized
override fun saveCache(url: String, t: ByteArray) {
if (t.size > maxMemorySize)
return
cacheMap[url] = t
cacheSize += t.size
while (cacheSize > maxMemorySize && cacheMap.isNotEmpty()) {
cacheSize.getAndAdd(t.size.toLong())
while (cacheSize.get() > maxMemorySize && cacheMap.isNotEmpty()) {
val byteArray = cacheMap.remove(cacheMap.keys.first())
cacheSize -= byteArray?.size ?: 0
cacheSize.getAndAdd(-(byteArray?.size ?: 0).toLong())
}
}

@Synchronized
override fun getCache(url: String): ByteArray? {
return cacheMap[url]
}
Expand Down

0 comments on commit f589cd4

Please sign in to comment.