Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java object serialization - thread safe?

I am writing highly concurrent application, which is extensively modifies objects of MyClass. The class is composed of several fields. My question is how to prevent modifications of particular object during its serialization by another thread?

Regards, Matt

like image 661
jan Avatar asked Oct 23 '10 11:10

jan


2 Answers

By synchronizing both the methods which serialize and modify the object state.

like image 123
Darin Dimitrov Avatar answered Nov 17 '22 00:11

Darin Dimitrov


Why modify MyClass? A better approach (and much easier to deal with concurrently) is to create new immutable versions of your state object and CAS them with an AtomicReference when updating. Eg:

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 as you are dealing with an immutable object. Your stored reference can only change from one valid state to another, and multiple updates can be performed atomically.

like image 35
Jed Wesley-Smith Avatar answered Nov 16 '22 23:11

Jed Wesley-Smith