JavaRush /Java Blog /Random EN /How serialization works in Java
ramhead
Level 13

How serialization works in Java

Published in the Random EN group
In this article, we will explain what serialization is and how it works in Java. How Serialization Works in Java - 1

Introduction

Object serialization is the ability of an object to store a complete copy of itself and any other objects it references using an output stream (for example, to an external file). This way, the object can be recreated from the serialized (saved) copy a little later when needed. Object serialization, a new feature introduced in JDK 1.1, provides a function for converting groups or individual objects, into a bitstream or byte array, for storage or transmission over a network. And as stated, a given bit stream or byte array can be converted back into Java objects. This mainly happens automatically thanks to the ObjectInputStreamand classes ObjectOutputStream. The programmer may decide to implement this functionality by implementing the interface Serializablewhen creating the class. The process of serialization is also known as object marshaling , while deserialization is known as unmarshaling . Serialization is a mechanism that allows an object to save a copy of itself and all other objects referenced by that object to an external file using the ObjectOutputStream. The saved objects can be data structures, diagrams, class objects JFrame, or any other objects, regardless of their type. At the same time, serialization stores information about what type an object is so that later, when deserialized, that information is used to recreate the exact type of object it was. So, serialization provides the following capabilities:
  • A system for storing objects, i.e.: saving their properties to an external file, to disk or to a database.
  • Remote procedure call system.
  • An object distribution system, for example, in software components such as COM, COBRA.
  • System for identifying changes in variable data over time.
To fully understand the concept of serialization, you need to have a clear understanding of the other two concepts—object persistence and thread persistence. Here we will talk a little about each of them in order to remember. A full explanation of them would require a separate chapter for each of these concepts.

Streams:

Every program must write its data to a storage location or pipe, and every program must read data from a pipe or storage location. In Java, these channels where programs write to and from which programs read data are called Streams ( Stream) . How Serialization Works in Java - 2
Figure 1. Graphical representation of Threads
Streams are mainly divided into two types:
  • Byte stream classes called *Streams
  • Character stream classes called *Reader and *Writer
Each data writing stream contains a set of writing methods. And each data reading thread, accordingly, has a similar set of reading methods. Once the thread is created, all these methods must be called.

Persistence

Object persistence is the ability of an object to live or, in other words, to “survive” the execution of a program. This means that any object that was created at runtime is destroyed by the JVM scavenger whenever that object is no longer used. But if the persistence API is implemented, these objects will not be destroyed by the JVM scavenger, instead they will be allowed to “live”, which also makes it possible to access them the next time the application is launched. In other words, persistence means that there is a lifetime for an object, independent of the lifetime of the application that is running. One way to implement persistence is to store objects somewhere in an external file or database, and then restore them at a later time using those files or the database as sources. This is where serialization comes into play. Any non-persistent object exists as long as the JVM is running. Serialized objects are simply objects converted into streams, which are then saved to an external file or transferred over a network for storage and recovery.

Implementation of the Serializable interface

Any class must implement an interface java.io.Serializableto serialize objects of that class. The interface Serializablehas no methods and only marks the class so that it can be identified as serializable. Only the fields of a serialized class object can be saved. Methods or constructors are not stored as part of the serialized stream. If any object acts as a reference to another object, then that object's fields are also serialized if that object's class implements the interface Serializable. In other words, the graph of this object thus obtained is completely serializable. An object graph includes a tree or structure of fields of an object and its subobjects. Two main classes that help implement the interface Seriliazable:
  • ObjectInputStream
  • ObjectOutputStream
Listing 1. Example of a simple class to show serialization
import java.io.*;
public class RandomClass implements Serializable {
 // Генерация рандомного значения
 private static int r() {
        return (int)(Math.random() * 10);
 }
    private int data[];
    // Конструктор
public RandomClass() {
        datafile = new int[r()];
        for (int i=0; i<datafile.length; i++)
        datafile[i]=r();
 }
    public void printout() {
 System.out.println("This RandomClass has "+datafile.length+" random integers");
 for (int i=0; i<datafile.length; i++) {
        System.out.print(datafile[i]+":");
        System.out.println();
    }
}
In the above code, a class is created that is serializable because "marked" by the serialization interface. The class creates an array of random integers when an instance of it is created. The code below shows the ability to write objects to a stream using the ObjectOutputStream. The program has an array of integers, but for serialization we don't have to iterate over its internal objects. The interface Seriliazabletakes care of this automatically. Listing 2. A simple example of serializing objects for output to a file
import java.io.*;
import java.util.*;
public class OutSerialize {
    public static void main (String args[]) throws IOException {
        RandomClass rc1 = new RandomClass();
        RandomClass rc2 = new RandomClass();
//создание цепи потоков с потоком вывода an object в конце
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("objects.dat"));
        Date now = new Date(System.currentTimeMillis());
//java.util.* был импортирован для использования класса Date
        out.writeObject(now);
        out.writeObject(rc1);
        out.writeObject(rc2);
out.close();
        System.out.println("I have written:");
System.out.println("A Date object: "+now);
        System.out.println("Two Group of randoms");
rc1.printout();
rc2.printout();
 }
}
The code below demonstrates the capabilities of the class ObjectInputStream, which reads serialized data from an external file into a program. Note that the objects are read in the same order in which they were written to the file. Listing 3. Reading serialized objects or Deserializing
import java.io.*;
import java.util.*;
public class InSerialize {
 public static void main (String args[]) throws  IOException, ClassNotFoundException {
    ObjectInputStream in =  new ObjectInputStream (new FileInputStream("objects.dat"));
 Date d1 = (Date)in.readObject();
 RandomClass rc1 = (RandomClass)in.readObject();
    RandomClass rc2 = (RandomClass)in.readObject();
    System.out.println("I have read:");
    System.out.println("A Date object: "+d1);
    System.out.println("Two Group of randoms");
    rc1.printout();
rc2.printout();
 }
}
Almost all Java classes can be serialized, including AWT classes. A frame, which is a window, contains a set of graphical components. If the frame is serialized, the serialization engine takes care of this and serializes all its components and data (position, content, etc.). Some Java class objects cannot be serialized because they contain data that references ephemeral operating system resources. For example classes java.io.FileInputStreamand java.lang.Thread. If an object contains references to non-serializable elements, the entire serialization operation will fail and an exception will be thrown NotSerializableException. If any object refers to a reference of an unserialized object, then it can be serialized using the transient keyword . Listing 4. Creating serializable objects using the transient keyword
public class Sclass implements Serializable{
public transient Thread newThread;
//помните, что поток(поток параллельного исполнения) по умолчанию не сериализуемый класс
    private String studentID;
    private int sum;
}

Security in Serialization

Serializing a class in Java involves passing all its data to an external file or database via a stream. We can limit the data that will be serialized whenever we wish. There are two ways to do this:
  • Each class parameter declared as transient is not serialized (by default, all class parameters are serialized)
  • Or, each parameter of the class that we want to serialize is marked with a tag Externalizable(by default, no parameters are serialized).
A data field will not be serialized with ObjectOutputStream, when called on an object, if that object's data field is marked transient . For example: private transient String password. On the other hand, to explicitly declare an object's data as serializable, we must mark the class as ExternalizablewriteExternalexplicitly readExteranlwriting and reading that object's data.

Conclusion

The feature of object serialization is used in many distributed systems as a way to transfer data. But serialization reveals hidden details, thus destroying the authenticity of abstract data types, which in turn destroys encapsulation. At the same time, it is nice to know that the data of the serialized object is the same data that was in the original, original object. This is also a great opportunity to implement an interface ObjectInputValidationand override a method validateObject(), even if multiple lines of code are used. If the object is not found, then we can throw an exception appropriately InvalidObjectException. Original article: How serialization works in Java
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION