What Is [Serializable] and When Should I Use It

What is [Serializable] and when should I use it?


What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

When should we implement Serializable interface?


  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of
    objects, put them on a disk or send
    them through a wire or wireless
    transport mechanism, then later,
    perhaps on another computer, reverse
    the process: resurrect the original
    object(s). The basic mechanisms are to
    flatten object(s) into a
    one-dimensional stream of bits, and to
    turn that stream of bits back into the
    original object(s).

    Like the Transporter on Star Trek,
    it's all about taking something
    complicated and turning it into a flat
    sequence of 1s and 0s, then taking
    that sequence of 1s and 0s (possibly
    at another place, possibly at another
    time) and reconstructing the original
    complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

Why do we use serialization?

Technically on the low-level, your serialized object will also end up as a stream of bytes on your cable or your filesystem...

So you can also think of it as a standardized and already available way of converting your objects to a stream of bytes. Storing/transferring object is a very common requirement, and it has less or little meaning to reinvent this wheel in every application.

As other have mentioned, you also know that this object->stream_of_bytes implementation is quite robust, tested, and generally architecture-independent.

This does not mean it is the only acceptable way to save or transfer an object: in some cases, you'll have to implement your own methods, for example to avoid saving unnecessary/private members (for example for security or performance reasons). But if you are in a simple case, you can make your life easier by using the serialization/deserialization of your framework, language or VM instead of having to implement it by yourself.

Hope this helps.

What is a serialVersionUID and why should I use it?

The docs for java.io.Serializable are probably about as good an explanation as you'll get:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an
InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class — serialVersionUID fields are not useful as inherited members.

Why use serialization

Serialization is useful any time you want to move a representation of your data into or out of your process boundary.

Saving an object to disk is a trivial example you'll see in many tutorials.

More commonly, serialization is used to transfer data to and from a web service, or to persist data to or from a database.

What is the purpose of Serialization in Java?

Let's define serialization first, then we can talk about why it's so useful.

Serialization is simply turning an existing object into a byte array. This byte array represents the class of the object, the version of the object, and the internal state of the object. This byte array can then be used between JVM's running the same code to transmit/read the object.

Why would we want to do this?

There are several reasons:

  • Communication: If you have two machines that are running the same code, and they need to communicate, an easy way is for one machine to build an object with information that it would like to transmit, and then serialize that object to the other machine. It's not the best method for communication, but it gets the job done.

  • Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval.

  • Deep Copy: If you need an exact replica of an Object, and don't want to go to the trouble of writing your own specialized clone() class, simply serializing the object to a byte array, and then de-serializing it to another object achieves this goal.

  • Caching: Really just an application of the above, but sometimes an object takes 10 minutes to build, but would only take 10 seconds to de-serialize. So, rather than hold onto the giant object in memory, just cache it out to a file via serialization, and read it in later when it's needed.

  • Cross JVM Synchronization: Serialization works across different JVMs that may be running on different architectures.

What does Serializable mean?

Serialization is persisting an object from memory to a sequence of bits, for instance for saving onto the disk. Deserialization is the opposite - reading data from the disk to hydrate/create an object.

In the context of your question, it is an interface that if implemented in a class, this class can automatically be serialized and deserialized by different serializers.

Should I use Serializable for my DTO and why should I use?

You don't need to implement Serializable and Deserializable for your DTO because it is already handled by Spring Boot Jackson Package.

What is Serializable in Java?

serializable is a special interface that specifies that class is serialiazable. It's special in that unlike a normal interface it does not define any methods that must be implemented: it is simply marking the class as serializable. For more info see the Java docs.

As to what "serializable" means it simply means converting an instance of a class (an object) into a format where it can be written to disk, or possibly transmitted over a network. You could for example save your object to disk and reload it later, with all the field values and internal state saved. See the wikipedia page for more info.



Related Topics



Leave a reply



Submit