gpt4 book ai didi

java - 如何使列表线程安全以进行序列化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:32:23 25 4
gpt4 key购买 nike

我正在使用 ThreadSafeList,我从中获得了很大的好处,可以将数据从进程流式传输到网络服务器,然后在数据进入客户端时将数据流式传输回来。在内存中,我使用 Spring Caching(引擎盖下的 ehcache)将数据保存在 JVM 中,一切都很好。当我开始达到我的堆限制并且 Spring Caching 在我使用它时开始将我的 ThreadSafeList 序列化到磁盘时,问题就开始了,导致 ConcurrentModificationExceptions。是否可以覆盖Serialization接口(interface)的私有(private)writeObject和readObject方法来解决问题?我不确定该怎么做,或者我是否应该放弃我的 ThreadSafeList。

当我开始这个程序时,我使用的是 BlockingDeque,但这还不够,因为当我放置和采用结构时,我不记得要缓存的数据......我不能使用 ConcurrentMap,因为我需要在我的列表中排序...我应该使用 ConcurrentNavigableMap 吗?我觉得自己使用 ThreadSafeList 和自定义私有(private)序列化函数可能是一种浪费?

Java Code Geeks ThreadSafeList

最佳答案

Collections.synchronizedList() 将使任何 List 线程安全并支持序列化(如果底层列表是可序列化的)。如果您需要对其进行迭代,请记住在列表上进行同步。

例如

@Cacheable
public List<String> getData(String clientName) {
List<String> data = Collections.synchronizedList(new ArrayList<String>());
// load data for the client from external process and add it to the list...
return data;
}

关于java - 如何使列表线程安全以进行序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com