【问题标题】:How to make a list thread-safe for serialization?如何使列表线程安全以进行序列化?
【发布时间】:2015-05-29 07:58:53
【问题描述】:

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

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

Java Code Geeks ThreadSafeList

【问题讨论】:

  • Spring 缓存不是这样的,如果它可以帮助您追踪问题的来源。

标签: java multithreading java.util.concurrent concurrentmodification spring-cache


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    相关资源
    最近更新 更多