Why Java needs Serializable interface?
Asked Answered
R

13

121

We work heavily with serialization and having to specify Serializable tag on every object we use is kind of a burden. Especially when it's a 3rd-party class that we can't really change.

The question is: since Serializable is an empty interface and Java provides robust serialization once you add implements Serializable - why didn't they make everything serializable and that's it?

What am I missing?

Randarandal answered 13/1, 2009 at 22:55 Comment(3)
What if you want to make your own object Serializable? Or did I misunderstand something?Anana
I will still get NotSerializableException because all fields of my objects have to be serializableRandarandal
Completely agree with Pop Catalin and dmitry's "This Serializable trick is just one another wrong decision that has been taken decade or two ago". It doesn't matter how dangerous can be serialization. And it's not true that since declaration is explicit then "you know that you have to pay special attention": everyone who needs it first put "implements" stuff, and then think about implication if something went wrong. It could've been all clearer if they gave us a "Unserializable" interface to be applied on special cases.Derr
C
124

Serialization is fraught with pitfalls. Automatic serialization support of this form makes the class internals part of the public API (which is why javadoc gives you the persisted forms of classes).

For long-term persistence, the class must be able to decode this form, which restricts the changes you can make to class design. This breaks encapsulation.

Serialization can also lead to security problems. By being able to serialize any object it has a reference to, a class can access data it would not normally be able to (by parsing the resultant byte data).

There are other issues, such as the serialized form of inner classes not being well defined.

Making all classes serializable would exacerbate these problems. Check out Effective Java Second Edition, in particular Item 74: Implement Serializable judiciously.

Crt answered 13/1, 2009 at 23:37 Comment(8)
This is clearly the better answer, I am disappointed that the selected answer is not this, it seems the posted chose with a "Im annoyed because I have to declare things serializable" agenda in mind. Its an example of some one wanting to free whell and not heed the security and design lessons that have already been learned in the past.Stefan
@Crt what do you mean by persisted form of classes ? I followed that link but can't understand what you mean ? can you explain this please ?Cnidoblast
@Cnidoblast - The serialized form of the URL type (for example) defines what private fields the type must have and what order they must be declared in.Crt
@Crt Why does the order matter ?Cnidoblast
@Cnidoblast - I misspoke (that'll teach me to comment on 3 year old answers without rechecking the spec.) The field order does not matter. FYI: you can find the detailed requirements for serialization hereCrt
@Crt Hi. I'm the original poster of this question from 4 years ago, and I've just selected your answer as accepted, if it means anything. I think your answer is really the better one, and I was probably too immature to see it that way at the time. Fixing now :)Randarandal
If I want to give custom serialization with me data object itself, what standard interface should I implement?Kept
then why some frameworks, like kafka, when serializing data, don't mandate the instances to implement Serializable ?Encroachment
R
30

I think both Java and .Net people got it wrong this time around, would have been better to make everything serializable by default and only need to mark those classes that can't be safely serialized instead.

For example in Smalltalk (a language created in 70s) every object is serializable by default. I have no idea why this is not the case in Java, considering the fact that the vast majority of objects are safe to serialize and just a few of them aren't.

Marking an object as serializable (with an interface) doesn't magically make that object serializable, it was serializable all along, it's just that now you expressed something that the system could have found on his own, so I see no real good reason for serialization being the way it is now.

I think it was either a poor decision made by designers or serialization was an afterthought, or the platform was never ready to do serialization by default on all objects safely and consistently.

Rosenstein answered 13/1, 2009 at 23:59 Comment(7)
You need to take special care when designing and implementing a class to make sure that instances will be serialised in a sensible way. The serializable interface actually mean: "I, as a programmer, has understood the consequences of serialization and permit the JVM to serialize this"Basting
@Rolf Rander: most of the time you need not take any care at all, just mark the class serializable. If serialization would have been ON by defaul on all objects the mindset of every developer would have been different too, it would have been something natural to do to make a class serializable...Rosenstein
it would have added another concern to the list of good class design, like for example making sure you don't have memory leaks. Still, good class design more and more requires that your classes are serializable when they can be.Rosenstein
@Rolf, or, it could mean "I don't care how X serializes it, but X needs it to be serializable so I will implement Serializable", where X can be some interoperable logical library (such as HttpSession, for instance, no one cares if a form object is serialized).Teakettle
@Pop: I disagree with "good class design more and more requires that your classes are serializable when they can be": that is over-engineering. If there's no need for them to be serializable, why should they? It's yet another cost for class design/impl, and costs are only warranted by benefit. I actually seldom need anything to be serializable; including objects I do need to trasfer.Rede
@StaxMan, because realizing later that a you need to serialize a class and you can't, can be very costly. It's one of those case where little extra effort pays. This is especially true if you're writing a library and someone else will consume it without the source codeRosenstein
I completely agree with this answer. In many languages everything is serializable by default. And actually the same with JVM, because it is easy to use Reflection to access any class member, whether it is private or not. This Serializable trick is just one another wrong decision that has been taken decade or two ago, and one more addition to the annoyance when dealing with pure java, like some flaws in collection and string processing in standard library. Happily there's Kryo, but it is dependency and one needs to find it first. This is how built-in serialization should have been done.Fresh
H
23

Not everything is genuinely serializable. Take a network socket connection, for example. You could serialize the data/state of your socket object, but the essence of an active connection would be lost.

Handclap answered 13/1, 2009 at 22:59 Comment(5)
This would be my problem and if I weren't smart enough to try to serialize socket, I would find my error during debugging. However, now I'm in a situation when I can't use Java serialization at all because of 3rd party class which doesn't implement Serializable for no good reason.Randarandal
There are a few decent ways to handle this case, such as writing a Serializable wrapper class that knows how to read & write the key data of the 3rd party class; make the wrapped instance transient and override writeObject and readObject.Monodrama
Can you inherit from the required objects in your api and serialize those classes?Handclap
@Joel: It's a good idea, but still a hack. I guess this whole thing is just another tradeoff went wrong. Thanks for your comments.Randarandal
This is one of those rare examples which illustrates that all we really need is implements NotSerializable :)Circulation
P
13

The main role of Serializable in Java is to actually make, by default, all other objects nonserializable. Serialization is a very dangerous mechanism, especially in its default implementation. Hence, like friendship in C++, it is off by default, even if it costs a little to make things serializable.

Serialization adds constraints and potential problems since structure compatibility is not insured. It is good that it is off by default.

I have to admit that I have seen very few nontrivial classes where standard serialization does what I want it to. Especially in the case of complex data structures. So the effort you'd spend making the class serializble properly dwarves the cost of adding the interface.

Peshawar answered 14/1, 2009 at 0:7 Comment(0)
D
9

For some classes, especially those that represent something more physical like a File, a Socket, a Thread, or a DB connection, it makes absolutely no sense to serialize instances. For many others, Serialization may be problematic because it destroys uniqueness constraints or simply forces you to deal with instances of different versions of a class, which you may not want to.

Arguably, it might have been better to make everything Serializable by default and make classes non-serializable through a keyword or marker interface - but then, those who should use that option probably would not think about it. The way it is, if you need to implement Serializable, you'll be told so by an Exception.

Dungeon answered 13/1, 2009 at 23:4 Comment(0)
E
4

I think the though was to make sure you, as the programmer, know that your object my be serialized.

Erida answered 13/1, 2009 at 22:59 Comment(0)
I
3

Apparently everything was serializable in some preliminary designs, but because of security and correctness concerns the final design ended up as we all know.

Source: Why must classes implement Serializable in order to be written to an ObjectOutputStream?.

Indigestible answered 6/3, 2013 at 16:16 Comment(0)
C
1

Having to state explicitely that instances of a certain class are Serializable the language forces you to think about if you you should allow that. For simple value objects serialization is trivial, but in more complex cases you need to really think things through.

By just relying on the standard serialization support of the JVM you expose yourself to all kinds of nasty versioning issues.

Uniqueness, references to 'real' resources, timers and lots of other types of artifacts are NOT candidates for serialization.

Charitacharitable answered 14/1, 2009 at 12:18 Comment(0)
E
1

Read this to understand Serializable Interface and why we should make only few classes Serializable and also we shopuld take care where to use transient keyword in case we want to remove few fields from the storing procedure.

http://www.codingeek.com/java/io/object-streams-serialization-deserialization-java-example-serializable-interface/

Elmaleh answered 10/12, 2014 at 8:59 Comment(0)
P
0

Well, my answer is that this is for no good reason. And from your comments I can see that you've already learned that. Other languages happily try serializing everything that doesn't jump on a tree after you've counted to 10. An Object should default to be serializable.

So, what you basically need to do is read all the properties of your 3rd-party class yourself. Or, if that's an option for you: decompile, put the damn keyword there, and recompile.

Panzer answered 14/1, 2009 at 0:4 Comment(2)
Serialization adds constraints and potential problems since structure compatibility is not insured. IMHO, It is good that it is off by default.Peshawar
I'm not certain what you mean by "structure compatibility".Panzer
P
0

There are some things in Java that simply cannot be serialized because they are runtime specific. Things like streams, threads, runtime, etc. and even some GUI classes (which are connected to the underlying OS) cannot be serialized.

Pneumodynamics answered 27/8, 2009 at 14:55 Comment(0)
H
0

While I agree with the points made in other answers here, the real problem is with deserialisation: If the class definition changes then there's a real risk the deserialisation won't work. Never modifying existing fields is a pretty major commitment for the author of a library to make! Maintaining API compatibility is enough of a chore as it is.

Hayner answered 2/10, 2013 at 5:31 Comment(2)
This is not correct. You need to read the Versioning of Serializable Objects chapter of the Object Serialization Specification, which wouldn't exist if what you claim here was true. The class definition can change within rather wide limits before it becomes incompatible with prior serializations. And it certainly isn't the answer to the question. The real reason has to do with security concerns.Platinumblond
@EJP, in the interest of truthiness I've edited my answer to reflect your points. The sentiment stands though, it is a big commitment that should definitely be opt-in rather than opt-outHayner
F
0

A class which needs to be persisted to a file or other media has to implement Serializable interface, so that JVM can allow the class object to be serialized. Why Object class is not serialized then none of the classes need to implement the interface, after all JVM serializes the class only when I use ObjectOutputStream which means the control is still in my hands to let the JVM to serialize.

The reason why Object class is not serializable by default in the fact that the class version is the major issue. Therefore each class that is interested in serialization has to be marked as Serializable explicitly and provide a version number serialVersionUID.

If serialVersionUID is not provided then we get unexpected results while deserialzing the object, that is why JVM throws InvalidClassException if serialVersionUID doesn't match. Therefore every class has to implement Serializable interface and provide serialVersionUID to make sure the Class presented at the both ends is identical.

Favored answered 8/7, 2016 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.