Serializing in java: automatic thread-safety?

2019-06-23 17:32发布

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?

3条回答
We Are One
2楼-- · 2019-06-23 17:38

Through serializing, is that object automatically somewhat "deep copied" and do you automatically get thread safety on that object?

It is not clear what you mean but ...

  • The process of serialization is NOT thread safe. For instance, if one thread serializes an object while another is changing it, the serialized object (i.e. the sequence of bytes) may not represent a consistent snapshot of the object.

  • Once serialized, the sequence of bytes is typically not accessible to a thread that could mess with it, so thread-safety is not an issue.

  • When the sequence of bytes is deserialized, you get completely new objects. There can be no thread-safety issues with these objects unless the thread that deserializes them also publishes them to other threads.

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?

It makes no difference whether the objects are deserialized in the same address space as they were serialized. The deserialization creates new objects. They are copies of the original objects.

查看更多
可以哭但决不认输i
3楼-- · 2019-06-23 17:44

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.

查看更多
时光不老,我们不散
4楼-- · 2019-06-23 17:52

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.

查看更多
登录 后发表回答