线程安全缓存ConcurrentLinkedHashMap,Kotlin

线程安全缓存ConcurrentLinkedHashMap,Kotlin

LinkedHashMap实现LRU缓存cache机制,Kotlin_zhangphil的博客-CSDN博客* * 基于Java LinkedList,实现Android大数据缓存策略 * 作者:Zhang Phil * 原文出处:http://blog.csdn.net/zhangphil * * 实现原理:原理的模型认为:在LinkedList的头部元素是最旧的缓存数据,在L_android大数据缓存。一句话概括的说:两者最大的不同就是,HashMap不保证put进去的数据的顺序;例如,假如在HashMap中依次、顺序添加元素:1,2,3,4,5,在遍历HashMap时输出的顺。https://blog.csdn.net/zhangphil/article/details/132604797上文利用LinkedHashMap固有特性发展出一种简洁的LRU缓存实现,在一些轻量级、小型LRU业务场景中,可以轻快构建出一个缓存模块,但并不是线程安全的。Google借鉴LinkedHashMap思想发展出线程安全的ConcurrentLinkedHashMap缓存实现。

GitHub - ben-manes/concurrentlinkedhashmap: A ConcurrentLinkedHashMap for JavaA ConcurrentLinkedHashMap for Java. Contribute to ben-manes/concurrentlinkedhashmap development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/ben-manes/concurrentlinkedhashmap

引入:

        <!-- https://mvnrepository.com/artifact/com.googlecode.concurrentlinkedhashmap/concurrentlinkedhashmap-lru -->
        <dependency>
            <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
            <artifactId>concurrentlinkedhashmap-lru</artifactId>
            <version>1.4.2</version>
        </dependency>

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap
import com.googlecode.concurrentlinkedhashmap.EvictionListener

fun main(args: Array<String>) {
    val CACHE_LIMIT = 3L

    val map = ConcurrentLinkedHashMap.Builder<Int, String>()
        .maximumWeightedCapacity(CACHE_LIMIT)
        .listener(object : EvictionListener<Int, String> {
            //当LRU缓存的头部元素删除时候回调。
            override fun onEviction(p0: Int?, p1: String?) {
                println("onEviction $p0-$p1")
            }
        })
        .build()

    map[1] = "a"
    map[2] = "b"
    map[3] = "c"
    println("- $map")

    map[4] = "d"
    println("-- $map")

    println(map[3])
    println("--- $map")
}

- {1=a, 2=b, 3=c}
onEviction 1-a
-- {2=b, 3=c, 4=d}
c
--- {2=b, 3=c, 4=d}

ConcurrentLinkedHashMap和LinkedHashMap有一个不同点是,LinkedHashMap在访问存储的元素后,会将被访问的元素移动到最尾部(设置访问order=true),而ConcurrentLinkedHashMap则没有这步操作,元素即便被访问,仍然保持原先顺序。

不管ConcurrentLinkedHashMap或者LinkedHashMap实现的缓存,比较适合小型、轻量级的缓存系统,如果是大型、功能要求复杂、要求高性能的业务场景,谷歌建议使用caffeine:

扫描二维码关注公众号,回复: 16431416 查看本文章

GitHub - ben-manes/caffeine: A high performance caching library for JavaA high performance caching library for Java. Contribute to ben-manes/caffeine development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/ben-manes/caffeinecaffeine是一种更现代化的、高性能、功能强大的LRU缓存框架。

高性能内存缓存框架Caffeine,Java_zhangphil的博客-CSDN博客高性能内存缓存框架Caffeine,Java。_内存缓存框架https://blog.csdn.net/zhangphil/article/details/126908710

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/132642121
今日推荐