Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing in java: automatic thread-safety?

If you serialize an object in Java and send it (over a socket) to nodes in a cluster do you automatically get thread safety?

Say you have a cluster and each node has several cores. The server has a Java Object that it wants to send to each core on each cluster to process. It serializes that object and sends it to each receiver.

Through serializing, is that object automatically somewhat "deep copied" and do you automatically get thread safety on that object? You aren't going to get any concurrency problems between the various nodes on the cluster because they can't be accessing the same place in memory... but what about between cores on the nodes?

like image 869
user651330 Avatar asked Jan 04 '12 08:01

user651330


People also ask

What does serializing do in Java?

To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

Is serialization thread safe in Java?

The serialization operation is not thread safe and it not a good idea to serilaize an object which is being modified. However any deep copy of the object, in the same thread, process or universe is a complete copy and is not changed when you change the original.

Which one is the correct method of serializing an object to a file?

The ObjectOutputStream class contains writeObject() method for serializing an Object. The ObjectInputStream class contains readObject() method for deserializing an object.

Is there any other method to avoid serialization?

To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.


1 Answers

The serialization operation is not thread safe and it not a good idea to serilaize an object which is being modified. However any deep copy of the object, in the same thread, process or universe is a complete copy and is not changed when you change the original.

Note: if you send the updated object again, you may not see the updates because it just sends a reference to the object. For this reason you should call reset() on the sender if you want to send an update. Another reason to use reset() is to avoid a "memory leak" as the sender and receiver will otherwise remember every object they ever wrote/read.

like image 86
Peter Lawrey Avatar answered Oct 02 '22 14:10

Peter Lawrey