SlideShare a Scribd company logo
Serialization



                1
Topics
●   What is Serialization?
●   What is preserved when an object is serialized?
●   Transient keyword
●   Process of serialization
●   Process of deserialization
●   Version control
●   Changing the default protocol
●   Creating your own protocol via Externalizable



                                                      2
What is
Serialization?
                 3
What is Serialization?
●   Ability to read or write an object to a stream
    –   Process of "flattening" an object
●   Used to save object to some permanent storage
    –   Its state should be written in a serialized form to a
        file such that the object can be reconstructed at a
        later time from that file
●   Used to pass on to another object via the
    OutputStream class
    –   Can be sent over the network




                                                                4
Streams Used for Serialization
●   ObjectOutputStream
    –   For serializing (flattening an object)
●   ObjectInputStream
    –   For deserializing (reconstructing an object)




                                                       5
Requirement for Serialization
●   To allow an object to be serializable:
     –   Its class should implement the Serializable interface
          ●   Serializable interface is marker interface
     –   Its class should also provide a default constructor (a
         constructor with no arguments)
●   Serializability is inherited
     –   Don't have to implement Serializable on every class
     –   Can just implement Serializable once along the
         class hierarchy




                                                                  6
Non-Serializable Objects
●   Most Java classes are serializable
●   Objects of some system-level classes are not
    serializable
    –   Because the data they represent constantly changes
         ●   Reconstructed object will contain different value
             anyway
         ●   For example, thread running in my JVM would be
             using my system's memory. Persisting it and trying to
             run it in your JVM would make no sense at all.
●   A NotSerializableException is thrown if you try to
    serialize non-serializable objects

                                                                     7
What is preserved
when an Object is
  serialized?
                    8
What is preserved when an object
          is serialized?
●   Enough information that is needed to reconstruct
    the object instance at a later time
    –   Only the object's data are preserved
    –   Methods and constructors are not part of the
        serialized stream
    –   Class information is included




                                                       9
Transient keyword

                    10
When to use transient keyword?
●   How do you serialize an object of a class that
    contains a non-serializable class as a field?
    –   Like a Thread object
●   What about a field that you don't want to to
    serialize?
    –   Some fields that you want to recreate anyway
    –   Performance reason
●   Mark them with the transient keyword
    –   The transient keyword prevents the data from being
        serialized
    –   Serialization does not care about access modifiers
        such as private -- all nontransient fields are
        considered part of an object's persistent state and   11
        are eligible for persistence
Example: transient keyword

1    class MyClass implements Serializable {
2

3        // Skip serialization of the transient field
4        transient Thread thread;
5        transient String fieldIdontwantSerialization;
6

7        // Serialize the rest of the fields
8        int data;
9        String x;
10

11       // More code
12   }
                                                         12
Process of
Serialization
                13
Serialization: Writing an Object
                 Stream
●   Use its writeObject method of the
    ObjectOutputStream class
    public final void writeObject(Object obj)
                                   throws IOException

    where,
    –   obj is the object to be written to the stream




                                                        14
Serialization: Writing an Object
                  Stream
1    import java.io.*;
2    public class SerializeBoolean {
3       SerializeBoolean() {
4          Boolean booleanData = new Boolean("true");
5          try {
6             FileOutputStream fos = new
7                         FileOutputStream("boolean.ser");
8             ObjectOutputStream oos = new
9                         ObjectOutputStream(fos);
10            oos.writeObject(booleanData);
11            oos.close();
12   //continued...

                                                             15
Serialization: Writing an Object
                  Stream
13           } catch (IOException ie) {
14               ie.printStackTrace();
15           }
16       }
17

18       public static void main(String args[]) {
19           SerializeBoolean sb = new SerializeBoolean();
20       }
21   }




                                                             16
Process of
Deserialization
                  17
Deserialization: Reading an Object
              Stream
●   Use its readObject method of the
    ObjectInputStream class
    public final Object readObject()
            throws IOException, ClassNotFoundException

    where,
    –   obj is the object to be read from the stream

●   The Object type returned should be typecasted to
    the appropriate class name before methods on that
    class can be executed


                                                         18
Deserialization: Reading an Object
              Stream
1    import java.io.*;
2    public class UnserializeBoolean {
3       UnserializeBoolean() {
4          Boolean booleanData = null;
5          try {
6             FileInputStream fis = new
7                            FileInputStream("boolean.ser");
8             ObjectInputStream ois = new
9                            ObjectInputStream(fis);
10            booleanData = (Boolean) ois.readObject();
11            ois.close();
12   //continued...

                                                               19
Deserialization: Reading an Object
              Stream
13          } catch (Exception e) {
14              e.printStackTrace();
15          }
16          System.out.println("Unserialized Boolean from "
17                             + "boolean.ser");
18          System.out.println("Boolean data: " +
19                             booleanData);
20          System.out.println("Compare data with true: " +
21                 booleanData.equals(new Boolean("true")));
22      }
23   //continued...



                                                               20
Deserialization: Reading an Object
              Stream
13       public static void main(String args[]) {
14            UnserializeBoolean usb =
15                              new UnserializeBoolean();
16        }
17   }




                                                            21
Version Control

                  22
Version Control: Problem Scenario
●   Imagine you create a class, instantiate it, and write
    it out to an object stream
●   That flattened object sits in the file system for some
    time
●   Meanwhile, you update the class file, perhaps
    adding a new field
●   What happens when you try to read in the flattened
    object?
      – An exception will be thrown -- specifically, the
        java.io.InvalidClassException
    –   Why? (See next slide)
                                                             23
Unique Identifier
●   Why exception is thrown?
    – Because all persistent-capable classes are
      automatically given a unique identifier
    –   If the identifier of the class does not equal the
        identifier of the flattened object, the exception
        will be thrown




                                                            24
Version Control: Problem Scenario
              Again
●
    However, if you really think about it, why
    should it be thrown just because I added a
    field? Couldn't the field just be set to its
    default value and then written out next time?
●
    Yes, but it takes a little code manipulation.
    The identifier that is part of all classes is
    maintained in a field called serialVersionUID.
●
    If you wish to control versioning, you simply
    have to provide the serialVersionUID field
    manually and ensure it is always the same,
    no matter what changes you make to the
    classfile.
                                                     25
How Do I generate a Unique ID?
         Use serialver utility
●   serialver utility is used to generate a unique ID
●   Example
     serialver MyClass
    MyClass static final long serialVersionUID =
     10275539472837495L;




                                                        26
Customizing
the Default Protocol
                       27
Provide your own readObject() and
      writeObject() methods
●   Used when the default behavior of readObject()
    and writeObject() are not sufficient
●   You provide your own readObject() and
    writeObject() in order to add custom behavior
●   Example
       // Provide your own readObject method
      private void readObject(ObjectInputStream in) throws IOException,
      ClassNotFoundException {

          // our "pseudo-constructor"
          in.defaultReadObject();
          // now we are a "live" object again, so let's run rebuild and start
          startAnimation();

      }                                                                         28
Creating Your own
Protocol via Externalizable
         interface
                              29
Externalizable Interface
●   The writeExternal and readExternal methods of the
    Externalizable interface can be implemented by a
    class to give the class complete control over the
    format and contents of the stream for an object and
    its supertypes
●   These methods must explicitly coordinate with the
    supertype to save its state
●   These methods supersede customized
    implementations of writeObject and readObject
    methods



                                                          30
How does Object Serialization
Scheme works with Externalizable
●   Object Serialization uses the Serializable and
    Externalizable interfaces
●   Each object to be stored is tested for the
    Externalizable interface
    –   If the object supports Externalizable, the
        writeExternal method is called
    –   If the object does not support Externalizable and
        does implement Serializable, the object is saved
        using ObjectOutputStream.




                                                            31
Thank You!



             32

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
Janu Jahnavi
 
Memory Management & Garbage Collection
Memory Management & Garbage CollectionMemory Management & Garbage Collection
Memory Management & Garbage Collection
Abhishek Sur
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
Young Alista
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Applets
AppletsApplets
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 

What's hot (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
Memory Management & Garbage Collection
Memory Management & Garbage CollectionMemory Management & Garbage Collection
Memory Management & Garbage Collection
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
Java awt
Java awtJava awt
Java awt
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Event handling
Event handlingEvent handling
Event handling
 
Applets
AppletsApplets
Applets
 
14 file handling
14 file handling14 file handling
14 file handling
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Java Strings
Java StringsJava Strings
Java Strings
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 

Viewers also liked

Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
Navneet Prakash
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Navneet Prakash
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Java beans
Java beansJava beans
Java beans
Ramraj Choudhary
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
Prashant Saini
 
Reflection and Introspection
Reflection and IntrospectionReflection and Introspection
Reflection and Introspection
adil raja
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
Carol McDonald
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained SimplyCiaran McHale
 
Reflection in java
Reflection in javaReflection in java
Reflection in javaupen.rockin
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
.NET Vs J2EE
.NET Vs J2EE.NET Vs J2EE
.NET Vs J2EE
ravikirantummala2000
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
Patroklos Papapetrou (Pat)
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Transaction management
Transaction managementTransaction management
Transaction managementrenuka_a
 

Viewers also liked (20)

Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
 
5java Io
5java Io5java Io
5java Io
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java beans
Java beansJava beans
Java beans
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
 
Reflection and Introspection
Reflection and IntrospectionReflection and Introspection
Reflection and Introspection
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
javabeans
javabeansjavabeans
javabeans
 
Java Reflection Explained Simply
Java Reflection Explained SimplyJava Reflection Explained Simply
Java Reflection Explained Simply
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
 
Java Beans
Java BeansJava Beans
Java Beans
 
.NET Vs J2EE
.NET Vs J2EE.NET Vs J2EE
.NET Vs J2EE
 
Javabeans
JavabeansJavabeans
Javabeans
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
 
Java beans
Java beansJava beans
Java beans
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Transaction management
Transaction managementTransaction management
Transaction management
 

Similar to Java Serialization

Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
NSConclave
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
Roman Atachiants
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
Shiv Sahni
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
GaddafiAdamu1
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
PRABHATMISHRA969924
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core DataInferis
 
Java 9
Java 9Java 9
Java 9
Netesh Kumar
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
catherinewall
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
04 threads
04 threads04 threads
04 threads
ambar khetan
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
MAYANKKUMAR492040
 
Java
Java Java
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Neelesh Shukla
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
Gagan Vishal Mishra
 
Automated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget ChainsAutomated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget Chains
Priyanka Aash
 

Similar to Java Serialization (20)

Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
core java
core javacore java
core java
 
Java 9
Java 9Java 9
Java 9
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
04 threads
04 threads04 threads
04 threads
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
 
Java
Java Java
Java
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Memory management
Memory managementMemory management
Memory management
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
Automated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget ChainsAutomated Discovery of Deserialization Gadget Chains
Automated Discovery of Deserialization Gadget Chains
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

Java Serialization

  • 2. Topics ● What is Serialization? ● What is preserved when an object is serialized? ● Transient keyword ● Process of serialization ● Process of deserialization ● Version control ● Changing the default protocol ● Creating your own protocol via Externalizable 2
  • 4. What is Serialization? ● Ability to read or write an object to a stream – Process of "flattening" an object ● Used to save object to some permanent storage – Its state should be written in a serialized form to a file such that the object can be reconstructed at a later time from that file ● Used to pass on to another object via the OutputStream class – Can be sent over the network 4
  • 5. Streams Used for Serialization ● ObjectOutputStream – For serializing (flattening an object) ● ObjectInputStream – For deserializing (reconstructing an object) 5
  • 6. Requirement for Serialization ● To allow an object to be serializable: – Its class should implement the Serializable interface ● Serializable interface is marker interface – Its class should also provide a default constructor (a constructor with no arguments) ● Serializability is inherited – Don't have to implement Serializable on every class – Can just implement Serializable once along the class hierarchy 6
  • 7. Non-Serializable Objects ● Most Java classes are serializable ● Objects of some system-level classes are not serializable – Because the data they represent constantly changes ● Reconstructed object will contain different value anyway ● For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all. ● A NotSerializableException is thrown if you try to serialize non-serializable objects 7
  • 8. What is preserved when an Object is serialized? 8
  • 9. What is preserved when an object is serialized? ● Enough information that is needed to reconstruct the object instance at a later time – Only the object's data are preserved – Methods and constructors are not part of the serialized stream – Class information is included 9
  • 11. When to use transient keyword? ● How do you serialize an object of a class that contains a non-serializable class as a field? – Like a Thread object ● What about a field that you don't want to to serialize? – Some fields that you want to recreate anyway – Performance reason ● Mark them with the transient keyword – The transient keyword prevents the data from being serialized – Serialization does not care about access modifiers such as private -- all nontransient fields are considered part of an object's persistent state and 11 are eligible for persistence
  • 12. Example: transient keyword 1 class MyClass implements Serializable { 2 3 // Skip serialization of the transient field 4 transient Thread thread; 5 transient String fieldIdontwantSerialization; 6 7 // Serialize the rest of the fields 8 int data; 9 String x; 10 11 // More code 12 } 12
  • 14. Serialization: Writing an Object Stream ● Use its writeObject method of the ObjectOutputStream class public final void writeObject(Object obj) throws IOException where, – obj is the object to be written to the stream 14
  • 15. Serialization: Writing an Object Stream 1 import java.io.*; 2 public class SerializeBoolean { 3 SerializeBoolean() { 4 Boolean booleanData = new Boolean("true"); 5 try { 6 FileOutputStream fos = new 7 FileOutputStream("boolean.ser"); 8 ObjectOutputStream oos = new 9 ObjectOutputStream(fos); 10 oos.writeObject(booleanData); 11 oos.close(); 12 //continued... 15
  • 16. Serialization: Writing an Object Stream 13 } catch (IOException ie) { 14 ie.printStackTrace(); 15 } 16 } 17 18 public static void main(String args[]) { 19 SerializeBoolean sb = new SerializeBoolean(); 20 } 21 } 16
  • 18. Deserialization: Reading an Object Stream ● Use its readObject method of the ObjectInputStream class public final Object readObject() throws IOException, ClassNotFoundException where, – obj is the object to be read from the stream ● The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed 18
  • 19. Deserialization: Reading an Object Stream 1 import java.io.*; 2 public class UnserializeBoolean { 3 UnserializeBoolean() { 4 Boolean booleanData = null; 5 try { 6 FileInputStream fis = new 7 FileInputStream("boolean.ser"); 8 ObjectInputStream ois = new 9 ObjectInputStream(fis); 10 booleanData = (Boolean) ois.readObject(); 11 ois.close(); 12 //continued... 19
  • 20. Deserialization: Reading an Object Stream 13 } catch (Exception e) { 14 e.printStackTrace(); 15 } 16 System.out.println("Unserialized Boolean from " 17 + "boolean.ser"); 18 System.out.println("Boolean data: " + 19 booleanData); 20 System.out.println("Compare data with true: " + 21 booleanData.equals(new Boolean("true"))); 22 } 23 //continued... 20
  • 21. Deserialization: Reading an Object Stream 13 public static void main(String args[]) { 14 UnserializeBoolean usb = 15 new UnserializeBoolean(); 16 } 17 } 21
  • 23. Version Control: Problem Scenario ● Imagine you create a class, instantiate it, and write it out to an object stream ● That flattened object sits in the file system for some time ● Meanwhile, you update the class file, perhaps adding a new field ● What happens when you try to read in the flattened object? – An exception will be thrown -- specifically, the java.io.InvalidClassException – Why? (See next slide) 23
  • 24. Unique Identifier ● Why exception is thrown? – Because all persistent-capable classes are automatically given a unique identifier – If the identifier of the class does not equal the identifier of the flattened object, the exception will be thrown 24
  • 25. Version Control: Problem Scenario Again ● However, if you really think about it, why should it be thrown just because I added a field? Couldn't the field just be set to its default value and then written out next time? ● Yes, but it takes a little code manipulation. The identifier that is part of all classes is maintained in a field called serialVersionUID. ● If you wish to control versioning, you simply have to provide the serialVersionUID field manually and ensure it is always the same, no matter what changes you make to the classfile. 25
  • 26. How Do I generate a Unique ID? Use serialver utility ● serialver utility is used to generate a unique ID ● Example serialver MyClass MyClass static final long serialVersionUID = 10275539472837495L; 26
  • 28. Provide your own readObject() and writeObject() methods ● Used when the default behavior of readObject() and writeObject() are not sufficient ● You provide your own readObject() and writeObject() in order to add custom behavior ● Example // Provide your own readObject method private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // our "pseudo-constructor" in.defaultReadObject(); // now we are a "live" object again, so let's run rebuild and start startAnimation(); } 28
  • 29. Creating Your own Protocol via Externalizable interface 29
  • 30. Externalizable Interface ● The writeExternal and readExternal methods of the Externalizable interface can be implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes ● These methods must explicitly coordinate with the supertype to save its state ● These methods supersede customized implementations of writeObject and readObject methods 30
  • 31. How does Object Serialization Scheme works with Externalizable ● Object Serialization uses the Serializable and Externalizable interfaces ● Each object to be stored is tested for the Externalizable interface – If the object supports Externalizable, the writeExternal method is called – If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream. 31