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
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.
No, ObjectOutputStream is not thread-safe.
List is not but implementation classes like ArrayLists are serializable.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With