This is a followup question to: Java. Serialization of objects in a multithreaded environment.
Suppose I have a collection of objects that are always acted upon by multiple threads.
public class AlwaysChanging implements Serializable {
// ... state ...
public synchronized void updateFromThread1( int data ) { /* ... */ }
public synchronized void updateFromThread2( int data ) { /* ... */ }
}
What is a safe way to serialize a Collection<AlwaysChanging>?
First of all, why do you have different update methods for different threads? This seems messy and inextensible.
To serialize the collection, you need to make sure that none of your
AlwaysChangingare changing during serialization. From this design, it seems the only way to do that would be to hold all of their locks prior to serialization. Alternatively, you could make a deep copy of the entire collection (copy all of the objects) and serialize that.Without knowing much about the rest of your application, I’d recommend looking into ReadWriteLock as a more finely-grained locking solution.