8

I understood from this posting that Serializable is incredibly easy to implement, and resilient to change (in most cases all you have to do is update the serialversionUID). If we want to control of read and write process we can implement Externalizable.

If all we want is the control of read and write process, we can override the below methods for serialization right? why do we need to introduce the new interface Externalizable?

private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;
 private void readObjectNoData()
     throws ObjectStreamException;
Community
  • 1
  • 1
james007
  • 741
  • 1
  • 12
  • 29
  • What posting? No link. – user207421 Jun 09 '14 at 01:00
  • 1
    Does this answer your question? [why we have Externalizable when we can override writeObject and readObject in java](https://stackoverflow.com/questions/16605376/why-we-have-externalizable-when-we-can-override-writeobject-and-readobject-in-ja) – Leponzo Apr 01 '21 at 20:36

1 Answers1

5

You ask:

why do we need to introduce the new interface Externalizable?

The best rationale I've been able to find (in Oracle documentation) is in the WebLogic JMS Best Practice document (original link):

"The CPU cost of serializing Java objects can be significant. This expense, in turn, affects JMS Object messages. You can offset this cost, to some extent, by having application objects implement java.io.Externalizable, but there still will be significant overhead in marshalling the class descriptor. To avoid the cost of having to write the class descriptors of additional objects embedded in an Object message, have these objects implement Externalizable, and call readExternal and writeExternal on them directly. For example, call obj.writeExternal(stream) rather than stream.writeObject(obj). Using Bytes and Stream messages is generally a preferred practice."

In short, you can get better performance using Externalizable, at least in some situations.

And "the difference" is that if you use Serializable the work of serialization is typically done for you, but with Externalizable you need to code it yourself.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Accessible link [here](http://web.archive.org/web/20141017081821/http://docs.oracle.com/cd/E15051_01/wls/docs103/jms/design_best_practices.html) (commented since the edit queue was full) – Leponzo Apr 01 '21 at 20:39