Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Penalty to implement Serializable in Java?

Is there a penalty to add

implements Serializable 

to a Java class? Impact on size of instantiated object or performance?

like image 796
AChoice Avatar asked May 03 '12 09:05

AChoice


People also ask

What will happen if we don't implement Serializable in Java?

The Student would not be Serializable, and it will act like a normal class. Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link.

What will happen if we don't implement Serializable?

If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException . All transient and static fields do not get serialized.

What happens if we implement Serializable interface in Java?

If a super class implements Serializable, then its sub classes do automatically. When an instance of a serializable class is deserialized, the constructor doesn't run. If a super class doesn't implement Serializable, then when a subclass object is deserialized, the super class constructor will run.

What are the disadvantages of Serializable?

If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.


1 Answers

There is no performance impact unless you perform serialization/deserialization but there are trade offs in terms of api design.

From Effective java by Joshua Bloch

  • A major cost of implementing Serializable is that it decreases the flexibility to change a class’s implementation once it has been released
  • A second cost of implementing Serializable is that it increases the likelihood of bugs and security holes
  • A third cost of implementing Serializable is that it increases the testing burden associated with releasing a new version of a class

Upto what extent these are applicable to you depend of your usecase.

like image 81
MoveFast Avatar answered Oct 02 '22 13:10

MoveFast