Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. 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.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

share|improve this question
    
Would you mind expanding a bit on what specifically in the referred article caused your question? –  gnat Mar 20 '13 at 14:09
    
@gnat - added the lines to the question. –  sky scraper Mar 20 '13 at 23:27

5 Answers 5

Serialization is mostly used in two areas:

  • prototyping of persistence

    pretty much every object graph can quickly be made serializable, for quick proof-of-concepts or quick-and-dirty applications this might be faster than setting up a real ORM layer or other persistence system

  • short term storage of almost-arbitrary objects:

    Applications servers, for example, have a tendency to persist session information using serialization. This has the advantage that the values in the session can be almost any type (as long as its serializable).

For almost all other uses, the drawbacks you (and the article) mentions are too big: the exact format is hard to keep stable, class changes can easily make your serialized data unreadable, reading/writing the data in non-Java code is almost impossible (or at least a lot harder than necessary).

JAXB and similar technologies provide similar functions with a similarly low cost, while reducing some of the problems.

share|improve this answer
    
I wouldn't call JAXB 'low cost' -- the schema has to be written. –  kevin cline Mar 20 '13 at 14:01
2  
@kevincline: you don't need a schema with JAXB, it's entirely optional (and you can even generate it from your classes, if you wish). Also: if JAXB is not useful for any reason, there are plenty of alternatives such as XML Beans work just as fine. –  Joachim Sauer Mar 20 '13 at 14:03

I use object serialization to allow post-mortem analysis in case of an unexpected error in production. The inputs to a calculation are serialized to a data file. If an error is reported, a simple program can reload the inputs and rerun the calculation with a debugger attached. Or a groovy shell can be used to reload the objects and modify them if desired.

We also use serialization to pass Java objects through HTTP to a web service. Much easier than serializing to and from text. The disadvantage is that the client and server installations must be deployed together, but that's not problem since we control both ends.

share|improve this answer
2  
That's an interesting use-case! Too small to call for a "more complex" system and most of the drawbacks don't apply! –  Joachim Sauer Mar 20 '13 at 14:10
    
We have now written a post-mortem analyzer that uses POI to build a spreadsheet from the Java objects for easier viewing. This has saved us many hours of log file examination. –  kevin cline Mar 20 '13 at 22:14

Serialization and an ORM / database are different things, although there is some overlap.

A serialized object represents all of the information needed to "thaw" a persisted object and repopulate its data. An ORM and database persist data to a database. A class can have fields of information that are not stored in the database by the ORM, for example computed field.

Additionally, serialization and an ORM are solving different problems. Serialization solves the problem of persisting an object graph to a stream (memory, file system, etc). An ORM handles the mapping of pieces of information to database columns and the retrieval and instantiation of objects, in addition to providing niceties such as searching and lazy loading.

Use an ORM when you want to persist data to a database for situations where you're dealing with large amounts of data or need reporting, searching / querying, warehousing or other things that databases are good at. Use serialization when you want to save a representation of your data structure(s) to disc.

share|improve this answer

Serialization is rarely used in practice.

As already mentioned the most common use case for serialization is to store objects as blobs in a session database. This works well for two reasons: sessions tend to be short lived, and the session database how no knowledge of how to map arbitrary objects to a relational model.

For data that needs to be retained for long periods of time (like an Amazon shopping cart) the best practice is to store that data in a database.

The session persistence mechanism ensures that a user with an active session is returned to the same server. The session database is only accessed when a server fails and the user is redirected to a new server. The new server detects an active session, but does not find it in memory, so it tries to retrieve it from the session database in an attempt to provide a seamless experience to the user.

There are two problems with this approach:

First, flushing session data to the session database is a slow process. Flushing session data too often degrades performance, and most servers are configured to flush every 30 seconds, or every minute, or longer. This "seemless" failover solution is never 100% effective.

Second, my experience is most clients agree that throwing up an error message asking the user to log in and try again during the rare instances that a server fails. In this case, we turn off the session database altogether and enjoy the performance boost.

Another use of serialization is to provide faster response times by using frameworks like Flex that use serialization and compression of object graphs for server-client interactions.

As other have pointed out, there are some creative and useful reasons to employ serialization, but these are rare in practice.

Historically serialization is difficult to implement correctly and reliability, restricting it's use to a small number of cases. Most developers will never serialize objects themselves, but may rely on frameworks who do it behind the scenes.

share|improve this answer

What are the advantages of serialization over non-serialization methods ?

Java serialization has some advantages:

  • Built into the system: You don't need to rely on third-party tools, libraries, or configuration.

  • Relatively simple to understand, at least in the beginning.

  • Every developer knows it (or should). Regardless of whether Java devs approve or disapprove, they are likely to be familiar with serialising Java objects.

And, of course, there are disadvantages:

  • Circumvents standard Java flow. Allocates memory but does not call a constructor, so transient fields are not initialised. Fields are initialised in alphabetical order, not source order.

  • Not so efficient in terms of space, but not horrible either. You may want to compress the result.

  • Brittle unless you take precautions when your objects change. And even then.

When should it be used and when should it be avoided ?

Use when:

  • Deployment size matters. Built into the system, so 0 extra bytes.

  • All actors will use compatible versions.

  • Long-term storage is not an issue.

Avoid when:

  • Any of the above do not apply.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.