Java object serialization - thread safety?

I am writing a very parallel application that intensively modifies MyClass objects. A class consists of several fields. My question is, how to prevent modifications to a particular object during its serialization by another thread?

Regards, Matt

+6
java multithreading concurrency
source share
2 answers

synchronize like methods that serialize and change the state of an object.

+7
source share

Why change MyClass? The best approach (and much easier to handle) is to create new, immutable versions of the state object and CAS using AtomicReference when updating. For example:

final class MyClass { final int age; final String name; final String address; MyClass(int age, String name, String address) {…} MyClass setNameAndAddress(String name, String address) {return new MyClass(age, name, address);} } 

Then serialization is not a problem, since you are dealing with an immutable object. Your saved link can only change from one valid state to another, and several updates can be performed atomically.

+4
source share

All Articles