🔏
Tech
  • 🟢App aspects
    • Software architecture
      • Caching
      • Anti-patterns
      • System X-ability
      • Coupling
      • Event driven architecture
        • Command Query Responsibility Segregation (CQRS)
        • Change Data Capture (CDC)
      • Distributed transactions
      • App dev notes
        • Architecture MVP
      • TEMP. Check list
      • Hexagonal arch
      • Communication
        • REST vs messaging
        • gRPC
        • WebSocket
      • Load balancers
      • Storage limits
      • Event storming
    • Authentication
    • Deployment strategy
  • Databases
    • Classification
    • DB migration tools
    • PostreSQL
    • Decision guidance
    • Index
      • Hash indexes
      • SSTable, LSM-Trees
      • B-Tree
      • Engines, internals
    • Performance
  • System design
    • Interview preparation
      • Plan
        • Instagram
        • Tinder
        • Digital wallet
        • Dropbox
        • Live video streaming
        • Uber
        • Whatsup
        • Tiktok
        • Twitter
        • Proximity service
    • Algorithms
    • Acronyms
  • 🟢Programming languages
    • Java
      • Features
        • Field hiding
        • HashCode() and Equals()
        • Reference types
        • Pass by value
        • Atomic variables
      • Types
      • IO / NIO
        • Java NIO
          • Buffer
          • Channel
        • Java IO: Streams
          • Input streams
            • BufferedInputStream
            • DataInputStream
            • ObjectInputStream
            • FilterInputStream
            • ByteArrayInputStream
        • Java IO: Pipes
        • Java IO: Byte & Char Arrays
        • Java IO: Input Parsing
          • PushbackReader
          • StreamTokenizer
          • LineNumberReader
          • PushbackInputStream
        • System.in, System.out, System.error
        • Java IO: Files
          • FileReader
          • FileWriter
          • FileOutputStream
          • FileInputStream
      • Multithreading
        • Thread liveness
        • False sharing
        • Actor model
        • Singleton
        • Future, CompletableFuture
        • Semaphore
      • Coursera: parallel programming
      • Coursera: concurrent programming
      • Serialization
      • JVM internals
      • Features track
        • Java 8
      • Distributed programming
      • Network
      • Patterns
        • Command
      • Garbage Collectors
        • GC Types
        • How GC works
        • Tools for GC
    • Kotlin
      • Scope functions
      • Inline value classes
      • Coroutines
      • Effective Kotlin
    • Javascript
      • Javascript vs Java
      • TypeScript
    • SQL
      • select for update
    • Python
  • OS components
    • Network
      • TCP/IP model
        • IP address in action
      • OSI model
  • 🟢Specifications
    • JAX-RS
    • REST
      • Multi part
  • 🟢Protocols
    • HTTP
    • OAuth 2.0
    • LDAP
    • SAML
  • 🟢Testing
    • Selenium anatomy
    • Testcafe
  • 🟢Tools
    • JDBC
      • Connection pool
    • Gradle
    • vim
    • git
    • IntelliJ Idea
    • Elastic search
    • Docker
    • Terraform
    • CDK
    • Argo CD
      • app-of-app setup
    • OpenTelemetry
    • Prometheus
    • Kafka
      • Consumer lag
  • 🟢CI
    • CircleCi
  • 🟢Platforms
    • AWS
      • VPC
      • EC2
      • RDS
      • S3
      • IAM
      • CloudWatch
      • CloudTrail
      • ELB
      • SNS
      • Route 53
      • CloudFront
      • Athena
      • EKS
    • Kubernetes
      • Networking
      • RBAC
      • Architecture
      • Pod
        • Resources
      • How to try
      • Kubectl
      • Service
      • Tooling
        • ArgoCD
        • Helm
        • Istio
    • GraalVM
    • Node.js
    • Camunda
      • Service tasks
      • Transactions
      • Performance
      • How it executes
  • 🟢Frameworks
    • Hibernate
      • JPA vs Spring Data
    • Micronaut
    • Spring
      • Security
      • JDBC, JPA, Hibernate
      • Transactions
      • Servlet containers, clients
  • 🟢Awesome
    • Нейробиология
    • Backend
      • System design
    • DevOps
    • Data
    • AI
    • Frontend
    • Mobile
    • Testing
    • Mac
    • Books & courses
      • Path: Java Concurrency
    • Algorithms
      • Competitive programming
    • Processes
    • Finance
    • Electronics
  • 🟢Electronics
    • Arduino
    • IoT
  • Artificial intelligence
    • Artificial Intelligence (AI)
  • 🚀Performance
    • BE
  • 📘Computer science
    • Data structures
      • Array
      • String
      • LinkedList
      • Tree
    • Algorithms
      • HowTo algorithms for interview
  • 🕸️Web dev (Frontend)
    • Trends
    • Web (to change)
  • 📈Data science
    • Time series
Powered by GitBook
On this page
  • Overview
  • Why do we need it?
  • How to make a class Serializable
  • Simple code example
  • Classes involved in serialization/deserialization
  • Caveats: Inheritance and Composition
  • Serial version UID
  • Custom serialization

Was this helpful?

  1. Programming languages
  2. Java

Serialization

PreviousCoursera: concurrent programmingNextJVM internals

Last updated 5 years ago

Was this helpful?

Overview

JDK1.1 Serialization is a process which translates a Java object into a sequence of bytes.

Why do we need it?

  • Normally the maximum life time of the object is from the program start till the program end. Serialization may help to keep object alive between the program executions.

  • Serialized object (as a byte stream) can be saved to the file and transferred by the network.

  • Serialization enables (Remote Method Invocation) to be performed.

How to make a class Serializable

The class needs to implement a marker interface to become a Serializable.

public class User implements Serializable {}

Simple code example

The example demonstrates a serializable class, which is being serialized and deserialized through saving to the file inside of the test.

public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	
	/**
	 * Static field belongs to the class, not to the instance.
	 * So it is not serialized.
	 */
	static String address = "theEarthPlanet";
	private int age;
	private String name;
	
	/**
	 * Transient fields are ignored during serialization.
	 */
	transient int height;

    // getters and setters of the fields
	}

Below is a test which performs serialization and deserialization of the user instance. Pay attention that transient class field height is ignored during the process of serialization.

public class SimpleSerialization {
	
	@Test
	public void whenSerializedAndDeserialized_objectIsTheSame() throws IOException, ClassNotFoundException {
	    // Arrange
		User user = new User();
		user.setAge(20);
		user.setName("theName");
		user.setHeight(180);
		
		String fileName = "theFile.txt";
		writeObjectToFile(user, fileName);
		
		// Act
		Object object = readObjectFromFile(fileName);
		User deserializedUser = (User) object;
		
		// Assert
		assertThat(deserializedUser.getAge()).isEqualTo(user.getAge());
		assertThat(deserializedUser.getName()).isEqualTo(user.getName());
		
		assertThat(deserializedUser.getHeight()).isNotEqualTo(user.getHeight());
	}
	
	
	private Object readObjectFromFile(String fileName) throws IOException, ClassNotFoundException {
		FileInputStream fileInputStream
				= new FileInputStream(fileName);
		ObjectInputStream objectInputStream
				= new ObjectInputStream(fileInputStream);
		Object object = objectInputStream.readObject();
		objectInputStream.close();
		return object;
	}
	
	
	private void writeObjectToFile(User user, String fileName) throws IOException {
		FileOutputStream fileOutputStream
				= new FileOutputStream(fileName);
		ObjectOutputStream objectOutputStream
				= new ObjectOutputStream(fileOutputStream);
		objectOutputStream.writeObject(user);
		objectOutputStream.flush();
		objectOutputStream.close();
	}
}

Classes involved in serialization/deserialization

public final void writeObject(Object o) throws IOException;

can write primitive types or graph of objects to an OutputStream as a stream of bytes. And streams can then be read using ObjectInputStream by the method

public final Object readObject() throws IOException, ClassNotFoundException;

Caveats: Inheritance and Composition

Serial version UID

It is strongly recommended that all serializable classes explicitly declare the private field ( this field is not useful for inheritance):

private static final long serialVersionUID = 42L;

Why do we need this field?

  • the serialization runtime associates each serializable class with a version number, so this field is a version number

    • if this field is not deliberately specified in serializable class

      • => serialization runtime calculate default serialVersionUID for this class based on its attributes, associated access modifiers

      • => when you add/modify any field in class, which is already serialized, => class will not be able to recover, because serialVersionUID generated for new class and for old serialized are different => exception java.io.InvalidClassException is thrown

  • this field is used during deserialization to verify that saved and loaded objects have the same attributes and thus are compatible on serialization

Custom serialization

A source code can be found .

Class ObjectOutputStream using a method

TODO Create a sequence diagram of serialization/deserialization.

When a class implements an interface java.io.Serializable all its subclasses are becoming serializable as well. There is an example of inheritance for serialization.

In case a class is composed of other classes, then each of these classes has to implement java.io.Serializable otherwise an exception NotSerializableException will be thrown during serialization process. On the diagram a class RootClass can be serialized. But during serialization of class Subclass an exception NotSerializableException is thrown, because one of the Subclass fields is a nonSerializable class (and it is important that value for this field is set, otherwise a field value is null and no exception is thrown during serialization). There is an example of composition for serialization.

There is an edge case when subclass implements Serializable, but parent class not. to javadoc. Only the fields of Serializable objects are written out and restored. In current case it means that for Child objects, assuming both value and name were set to the object only name field values will be serialized/deserialized. And there will be no Runtime exceptions in this case. And fields of non-serializable Parent class will be initialised using its no-args constructor (public or protected), so this constructor should be accessible to the Child class. There is an example, which demonstrates the edge case for inheritance.

There is an edge case for inheritance which will throw an exception in runtime. So the subclass Child is implementing Serializable, but its super class not. Plus there is not default constructor for super class Parent, it means that during deserialization there is no possibility to initialise fields from super class and exception java.io.InvalidClassException will be thrown in runtime (serialization happens without exceptions). There is an example, which demonstrates this edge case of throwing exception

There is an example where fragility of serialVersionUID is demonstrated.

TODO

🟢
⚠️
⚠️
here
example
✅
Java RMI
example
example
Link
example
example
Composition
Inheritance correct case
classes
Inheritance
Serialization
Inheritance incorrect case