Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list thread-safe for serialization?

I am using a ThreadSafeList and I am getting great mileage out of it for streaming data from a process to a webserver and then streaming the data back out as it comes in to a client. In memory I am saving the data in the JVM with Spring Caching (ehcache under the hood) and all is well. The trouble started when I started hitting my heap limits and Spring Caching started serializing my ThreadSafeList to disk while I am using it, causing ConcurrentModificationExceptions. Can I overwrite the private writeObject and readObject methods for the Serialization interface to solve the problem? I am unsure of how to do this or if I should abandon my ThreadSafeList.

Back when I started this program I was using a BlockingDeque, but it wasn't sufficient because as I put and take on the structure I couldn't remember the data for caching... I can't use a ConcurrentMap because I need ordering in my list... should I go for ConcurrentNavigableMap? I feel like rolling my own with a ThreadSafeList and custom private serialization functions might be a waste?

Java Code Geeks ThreadSafeList

like image 678
smuggledPancakes Avatar asked Mar 25 '15 14:03

smuggledPancakes


People also ask

Is serializable thread-safe?

Definitely it is "thread-safe" (in the sense that you are defining it). Serializing is by definition a deep copy of the object and each worker will get a different object.

Is ObjectOutputStream thread-safe?

No, ObjectOutputStream is not thread-safe.

Is List of string serializable?

List is not but implementation classes like ArrayLists are serializable.

Why are lists not thread-safe?

In fact, by default, classes are not thread-safe. Being thread-safe would mean that any operation modifying the list would need to be interlocked against simultaneous access. This would be necessary even for those lists that will only ever be used by a single thread. That would be very inefficient.


Video Answer


1 Answers

Collections.synchronizedList() will make any List thread-safe and supports serialization (if the underlying list is Serializable). Remember to synchronize on the list if you need to iterate over it.

e.g.

@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;
}
like image 76
teppic Avatar answered Sep 19 '22 14:09

teppic