When to use serialization?

Do not use serialization if you do not have to. A common use of serialization is to use it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database. Deep cloning or copy can be achieved through serialization. This may be fast to code but will have performance implications.
To serialize the above “Car” object to a file (sample for illustration purpose only, should use try {} catch {} block):

Car car = new Car(); // The “Car” class implements a java.io.Serializable interface
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(car); // serialization mechanism happens here
out.close();

The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to achieve scalability. Objects are passed in RMI (Remote Method Invocation) across network using serialization.

Tagged . Bookmark the permalink.

Leave a Reply