SlideShare a Scribd company logo
JOURNEY INTO THE WORLD OF JAVA:
JAVA SERIALIZATION
public class Vehicle{
public String number = "";
public Vehicle(){
System.out.println("Vehicle::Vehicle()");
}
}public class Car extends Vehicle implements Serializable{
public String mark = "";
public String model = "";
public Car(){
System.out.println("Car::Car()");
}
public Car(String mark, String model){
System.out.println("Car::Car(String, String)");
this.mark = mark;
this.model = model;
}
}
Serializable
public class Vehicle{
public String number = "";
public Vehicle(){
System.out.println("Vehicle::Vehicle()");
}
}
Serializable
public class Car extends Vehicle implements Serializable{
public String mark = "";
public String model = "";
public Car(){
System.out.println("Car::Car()");
}
public Car(String mark, String model){
System.out.println("Car::Car(String, String)");
this.mark = mark;
this.model = model;
}
}
Serializable
System.out.println("Creating...");
Car car = new Car("Zaz", "Forza");
car.number = "AA0001BP";
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
System.out.println("Serializing...");
objectOutputStream.writeObject(car);
objectOutputStream.flush();
byteArrayOutputStream.flush();
objectOutputStream.close();
byteArrayOutputStream.close();
ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
System.out.println("Deserializing...");
Car car2 = (Car)ois.readObject();
System.out.println("car2.number=" + car2.number);
System.out.println("car2.mark=" + car2.mark);
System.out.println("car2.model=" + car2.model);
Serializable
System.out.println("Creating...");
Car car = new Car("Zaz", "Forza");
car.number = "AA0001BP";
Serializable
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
System.out.println("Serializing...");
objectOutputStream.writeObject(car);
objectOutputStream.flush();
byteArrayOutputStream.flush();
objectOutputStream.close();
byteArrayOutputStream.close();
Serializable
ByteArrayInputStream bais = new
ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
System.out.println("Deserializing...");
Car car2 = (Car)ois.readObject();
System.out.println("car2.number=" + car2.number);
System.out.println("car2.mark=" + car2.mark);
System.out.println("car2.model=" + car2.model);
Serializable
Creating...
Vehicle::Vehicle()
Car::Car(String, String)
Serializing...
Deserializing...
Vehicle::Vehicle()
car2.number=
car2.mark=Zaz
car2.model=Forza
Serializable
Serializable. Secure
private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException;
private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException,
ClassNotFoundException;
private void java.io.ObjectInputStream.defaultWriteObject(java.io.ObjectOutputStream stream)
throws java.io.IOException;
private void java.io.ObjectInputStream.defaultReadObject(java.io.ObjectInputStream stream)
throws java.io.IOException,
ClassNotFoundException;
public interface java.io.ObjectInputValidation {
public void validateObject() throws InvalidObjectException;
}
Serializable. Features
public class ArrayList extends AbstractList implements List,
Cloneable,Serializable {
private transient Object elementData[];
private int size;
...
}
class List implements Serializable {
List next;
private static final ObjectStreamField[] serialPersistentFields
= {new ObjectStreamField("next", List.class)}
};
• Adding new fields to a class
• Changing the fields from static to nonstatic
• Changing the fields from transient to nontransient
Serializable. Can Manage Automatically
private static final long serialVersionUID = 3329999866918906824L;
private/public/protected Object readResolve() throws ObjectStreamException
private/public/protected Object writeReplace() throws ObjectStreamException
Serializable. Singleton
Serializable. Singleton
public class Singleton implements Serializable {
private static final long serialVersionUID = 8413502725007695828L;
private static Singleton instance = null;
public String name = "";
private Singleton(){};
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
private Object readResolve() throws ObjectStreamException{
instance.name = this.name;
return instance;
}
}
Serializable. Singleton
private Object readResolve() throws ObjectStreamException{
instance.name = this.name;
return instance;
}
}
Serializable. Singleton
Singleton instance1 = Singleton.getInstance();
instance1.name = "instance1";
............................................................................
System.out.println("Serializing...");
System.out.println("instance1.name:" + instance1.name);
..............................................................................
objectOutputStream.writeObject(instance1);
............................................................................
instance1.name = "instance2";
............................................................................
System.out.println("Deserializing...");
Singleton instance2 = (Singleton)ois.readObject();
if(instance1 == instance2){
System.out.println("instance1 == instance2");
}else{
System.out.println("instance1 != instance2");
}
System.out.println("instance2.name:" + instance2.name);
Serializable. Singleton
Singleton instance1 = Singleton.getInstance();
instance1.name = "instance1";
............................................................................
System.out.println("Serializing...");
System.out.println("instance1.name:" + instance1.name);
..............................................................................
objectOutputStream.writeObject(instance1);
............................................................................
instance1.name = "instance2";
Serializable. Singleton
............................................................................
System.out.println("Deserializing...");
Singleton instance2 = (Singleton)ois.readObject();
if(instance1 == instance2){
System.out.println("instance1 == instance2");
}else{
System.out.println("instance1 != instance2");
}
System.out.println("instance2.name:" + instance2.name);
Serializable. Singleton
Serializing...
instance1.name:instance1
Deserializing...
instance1 == instance2
instance2.name:instance1
Serializable. ENUM
public enum Color {
RED("red"),GREEN("green"),BLUE("blue");
private Color(String name){
this.name = name;
}
public String getName(){
return name;
}
private String name;
}
Serializable. ENUM
Color red1 = Color.RED;Color green1 = Color.GREEN;Color blue1 = Color.BLUE;
.....................................
System.out.println("Serializing...");
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(red1);
objectOutputStream.writeObject(green1);
objectOutputStream.writeObject(blue1);
.....................................
System.out.println("Deserializing...");
Color red2 = (Color)ois.readObject();
Color green2 = (Color)ois.readObject();
Color blue2 = (Color)ois.readObject();
if(red1 == red2) System.out.println("red1 == red2");
if(green1 == green2) System.out.println("green1 == green2");
if(blue1 == blue2) System.out.println("blue1 == blue2");
Serializable. ENUM
Color red1 = Color.RED;
Color green1 = Color.GREEN;
Color blue1 = Color.BLUE;
.....................................
System.out.println("Serializing...");
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(red1);
objectOutputStream.writeObject(green1);
objectOutputStream.writeObject(blue1);
Serializable. ENUM
.....................................
System.out.println("Deserializing...");
Color red2 = (Color)ois.readObject();
Color green2 = (Color)ois.readObject();
Color blue2 = (Color)ois.readObject();
if(red1 == red2) System.out.println("red1 == red2");
if(green1 == green2) System.out.println("green1 == green2");
if(blue1 == blue2) System.out.println("blue1 == blue2");
Serializable. ENUM
Serializing...
Deserializing...
red1 == red2
green1 == green2
blue1 == blue2
Serializable. ENUM
writeObject
writeReplace
serialPersistentFields
serialVersionUID
public interface Externalizable extends java.io.Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}
Externalizable
Externalizable. Performance
public class ItemExt implements Externalizable{
private int fieldInt;
private boolean fieldBoolean;
private long fieldLong;
private float fieldFloat;
private double fieldDouble;
private String fieldString;
public ItemExt(){
this(0,true,0,0,0,"");
}
..................................................
Externalizable. Performance
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(fieldInt);
out.writeBoolean(fieldBoolean);
out.writeLong(fieldLong);
out.writeFloat(fieldFloat);
out.writeDouble(fieldDouble);
out.writeUTF(fieldString);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
fieldInt = in.readInt();
fieldBoolean = in.readBoolean();
fieldLong = in.readLong();
fieldFloat = in.readFloat();
fieldDouble = in.readDouble();
fieldString = in.readUTF();
}
Externalizable. Performance
public abstract class ContainerExt implements Externalizable{
protected List<ItemExt> items;
public ContainerExt(){
items = new LinkedList<ItemExt>();
}
public void addItem(ItemExt item){
items.add(item);
}
..................................................
}
/*ContainerExt1*/public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(items);
}
public void readExternal(ObjectInput in) throws
IOException, ClassNotFoundException {
items = (List<ItemExt>)in.readObject();
}
Externalizable. Performance
Externalizable. Performance
/*ContainerExt2*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(items.size());
for(Externalizable ext : items)
out.writeObject(ext);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
int count = in.readInt();
for(int i=0; i<count; i++){
ItemExt ext = (ItemExt)in.readObject();
items.add(ext);
}
}
/*ContainerExt3*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(items.size());
for(Externalizable ext : items)
ext.writeExternal(out);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException{
int count = in.readInt();
for(int i=0; i<count; i++){
ItemExt ext = new ItemExt();
ext.readExternal(in);
items.add(ext);
}
}
Externalizable. Performance
[java] Creating 100000 objects
[java] Serializable: written in 971ms, readed in 1353
[java] Externalizable1: written in 1026ms, readed in 1129
[java] Externalizable2: written in 909ms, readed in 1876
[java] Externalizable3: written in 49ms, readed in 268
06/16/2013 08:24 PM 5,547,651 cont.ser
06/16/2013 08:24 PM 5,747,559 contExt1.ser
06/16/2013 08:24 PM 5,747,521 contExt2.ser
06/16/2013 08:24 PM 4,871,155 contExt3.ser
Externalizable. Performance
https://github.com/MikhailGevak/Serialize

More Related Content

What's hot (20)

PDF
Architectures in the compose world
Fabio Collini
 
PDF
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
PDF
Connect.Tech- Swift Memory Management
stable|kernel
 
PDF
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Fabio Collini
 
PPTX
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
PDF
droidparts
Droidcon Berlin
 
PDF
DynaMine: Finding Common Error Patterns by Mining Software Revision Histories
Thomas Zimmermann
 
PDF
Important java programs(collection+file)
Alok Kumar
 
DOCX
Abstract factory
Muthukumar P
 
PPTX
Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...
tdc-globalcode
 
PDF
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PDF
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
PPTX
Demystifying dependency Injection: Dagger and Toothpick
Danny Preussler
 
PDF
Managing parallelism using coroutines
Fabio Collini
 
PPTX
Qunit Java script Un
akanksha arora
 
PPTX
Dealing with combinatorial explosions and boring tests
Alexander Tarlinder
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
Java programs
Mukund Gandrakota
 
PDF
Best Java Problems and Solutions
Java Projects
 
Architectures in the compose world
Fabio Collini
 
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
Connect.Tech- Swift Memory Management
stable|kernel
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Fabio Collini
 
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
droidparts
Droidcon Berlin
 
DynaMine: Finding Common Error Patterns by Mining Software Revision Histories
Thomas Zimmermann
 
Important java programs(collection+file)
Alok Kumar
 
Abstract factory
Muthukumar P
 
Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...
tdc-globalcode
 
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
Demystifying dependency Injection: Dagger and Toothpick
Danny Preussler
 
Managing parallelism using coroutines
Fabio Collini
 
Qunit Java script Un
akanksha arora
 
Dealing with combinatorial explosions and boring tests
Alexander Tarlinder
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Java programs
Mukund Gandrakota
 
Best Java Problems and Solutions
Java Projects
 

Viewers also liked (20)

PPT
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
PPT
Доступность веб-сайтов: WWW для всех?
Ecommerce Solution Provider SysIQ
 
PPT
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
PDF
Unexpected achievements 2013
Ecommerce Solution Provider SysIQ
 
PDF
Developing for e commerce is important
Ecommerce Solution Provider SysIQ
 
PDF
User focused design
Ecommerce Solution Provider SysIQ
 
PDF
Speed Up Your Website
Ecommerce Solution Provider SysIQ
 
PPT
External Widgets Performance
Ecommerce Solution Provider SysIQ
 
PDF
QA evolution to the present day
Ecommerce Solution Provider SysIQ
 
PDF
User Behavior: Interacting With Important Website Elements
Ecommerce Solution Provider SysIQ
 
PDF
Manifest of modern engineers
Ecommerce Solution Provider SysIQ
 
PPT
Гибкость и Структурированность Oбъектно Oриентированноя CSS
Ecommerce Solution Provider SysIQ
 
PPT
Frontend Servers and NGINX: What, Where and How
Ecommerce Solution Provider SysIQ
 
PDF
Management and Communications (IPAA)
Ecommerce Solution Provider SysIQ
 
PDF
Lupan big enterprise ecommerce fusion 2013
Ecommerce Solution Provider SysIQ
 
PDF
Testing schools overview
Ecommerce Solution Provider SysIQ
 
PPT
Психология восприятия и UX дизайн
Ecommerce Solution Provider SysIQ
 
PDF
Getting to know magento
Ecommerce Solution Provider SysIQ
 
PDF
Seo and Marketing Requirements in Web Architecture
Ecommerce Solution Provider SysIQ
 
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Доступность веб-сайтов: WWW для всех?
Ecommerce Solution Provider SysIQ
 
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
Unexpected achievements 2013
Ecommerce Solution Provider SysIQ
 
Developing for e commerce is important
Ecommerce Solution Provider SysIQ
 
Speed Up Your Website
Ecommerce Solution Provider SysIQ
 
External Widgets Performance
Ecommerce Solution Provider SysIQ
 
QA evolution to the present day
Ecommerce Solution Provider SysIQ
 
User Behavior: Interacting With Important Website Elements
Ecommerce Solution Provider SysIQ
 
Manifest of modern engineers
Ecommerce Solution Provider SysIQ
 
Гибкость и Структурированность Oбъектно Oриентированноя CSS
Ecommerce Solution Provider SysIQ
 
Frontend Servers and NGINX: What, Where and How
Ecommerce Solution Provider SysIQ
 
Management and Communications (IPAA)
Ecommerce Solution Provider SysIQ
 
Lupan big enterprise ecommerce fusion 2013
Ecommerce Solution Provider SysIQ
 
Testing schools overview
Ecommerce Solution Provider SysIQ
 
Психология восприятия и UX дизайн
Ecommerce Solution Provider SysIQ
 
Getting to know magento
Ecommerce Solution Provider SysIQ
 
Seo and Marketing Requirements in Web Architecture
Ecommerce Solution Provider SysIQ
 
Ad

Similar to Java serialization (19)

PDF
Java Serialization Deep Dive
Martijn Dashorst
 
PPTX
Java Serialization Facts and Fallacies
Roman Elizarov
 
PDF
Java Serialization
imypraz
 
PPT
Java Serialization
jeslie
 
PDF
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
PPTX
File Handling - Serialization.pptx
UsamaAshraf55
 
PPT
22CS307-ADAVANCE JAVA PROGRAMMING UNIT 4
logesswarisrinivasan
 
PPTX
Javasession6
Rajeev Kumar
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PDF
Apache avro data serialization framework
veeracynixit
 
PDF
IO Streams, Serialization, de-serialization, autoboxing
Gurpreet singh
 
PPTX
Gulshan serialization inJava PPT ex.pptx
PRABHATMISHRA969924
 
PDF
Writing Usable APIs in Practice by Giovanni Asproni
SyncConf
 
ODP
Object Oriented Prograring(OOP) java
GaddafiAdamu1
 
PPS
Advance Java
Vidyacenter
 
PPT
Object Oriented Programming with Java
Jussi Pohjolainen
 
PPTX
interface in java explained in detailed form
PriyadharshiniG41
 
PDF
Serialization & De-serialization in Java
InnovationM
 
PPTX
Serialization and performance by Sergey Morenets
Alex Tumanoff
 
Java Serialization Deep Dive
Martijn Dashorst
 
Java Serialization Facts and Fallacies
Roman Elizarov
 
Java Serialization
imypraz
 
Java Serialization
jeslie
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
File Handling - Serialization.pptx
UsamaAshraf55
 
22CS307-ADAVANCE JAVA PROGRAMMING UNIT 4
logesswarisrinivasan
 
Javasession6
Rajeev Kumar
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
Apache avro data serialization framework
veeracynixit
 
IO Streams, Serialization, de-serialization, autoboxing
Gurpreet singh
 
Gulshan serialization inJava PPT ex.pptx
PRABHATMISHRA969924
 
Writing Usable APIs in Practice by Giovanni Asproni
SyncConf
 
Object Oriented Prograring(OOP) java
GaddafiAdamu1
 
Advance Java
Vidyacenter
 
Object Oriented Programming with Java
Jussi Pohjolainen
 
interface in java explained in detailed form
PriyadharshiniG41
 
Serialization & De-serialization in Java
InnovationM
 
Serialization and performance by Sergey Morenets
Alex Tumanoff
 
Ad

More from Ecommerce Solution Provider SysIQ (14)

PDF
Developing for e commerce is important
Ecommerce Solution Provider SysIQ
 
PDF
Magento code audit
Ecommerce Solution Provider SysIQ
 
PDF
Scalability and performance for e commerce
Ecommerce Solution Provider SysIQ
 
PDF
non-blocking java script
Ecommerce Solution Provider SysIQ
 
PDF
Quick Intro to Clean Coding
Ecommerce Solution Provider SysIQ
 
PDF
QA evolution, in pictures
Ecommerce Solution Provider SysIQ
 
PDF
Databases on Client Side
Ecommerce Solution Provider SysIQ
 
PPTX
IGears: Template Architecture and Principles
Ecommerce Solution Provider SysIQ
 
PPT
Interactive web prototyping
Ecommerce Solution Provider SysIQ
 
PPT
Модульные сетки в реальном мире
Ecommerce Solution Provider SysIQ
 
PPT
Правила хорошего SEO тона в Frontend разработке
Ecommerce Solution Provider SysIQ
 
PPT
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 
Developing for e commerce is important
Ecommerce Solution Provider SysIQ
 
Scalability and performance for e commerce
Ecommerce Solution Provider SysIQ
 
non-blocking java script
Ecommerce Solution Provider SysIQ
 
Quick Intro to Clean Coding
Ecommerce Solution Provider SysIQ
 
QA evolution, in pictures
Ecommerce Solution Provider SysIQ
 
Databases on Client Side
Ecommerce Solution Provider SysIQ
 
IGears: Template Architecture and Principles
Ecommerce Solution Provider SysIQ
 
Interactive web prototyping
Ecommerce Solution Provider SysIQ
 
Модульные сетки в реальном мире
Ecommerce Solution Provider SysIQ
 
Правила хорошего SEO тона в Frontend разработке
Ecommerce Solution Provider SysIQ
 
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 

Recently uploaded (20)

PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 

Java serialization

  • 1. JOURNEY INTO THE WORLD OF JAVA: JAVA SERIALIZATION
  • 2. public class Vehicle{ public String number = ""; public Vehicle(){ System.out.println("Vehicle::Vehicle()"); } }public class Car extends Vehicle implements Serializable{ public String mark = ""; public String model = ""; public Car(){ System.out.println("Car::Car()"); } public Car(String mark, String model){ System.out.println("Car::Car(String, String)"); this.mark = mark; this.model = model; } } Serializable
  • 3. public class Vehicle{ public String number = ""; public Vehicle(){ System.out.println("Vehicle::Vehicle()"); } } Serializable
  • 4. public class Car extends Vehicle implements Serializable{ public String mark = ""; public String model = ""; public Car(){ System.out.println("Car::Car()"); } public Car(String mark, String model){ System.out.println("Car::Car(String, String)"); this.mark = mark; this.model = model; } } Serializable
  • 5. System.out.println("Creating..."); Car car = new Car("Zaz", "Forza"); car.number = "AA0001BP"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); System.out.println("Serializing..."); objectOutputStream.writeObject(car); objectOutputStream.flush(); byteArrayOutputStream.flush(); objectOutputStream.close(); byteArrayOutputStream.close(); ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); System.out.println("Deserializing..."); Car car2 = (Car)ois.readObject(); System.out.println("car2.number=" + car2.number); System.out.println("car2.mark=" + car2.mark); System.out.println("car2.model=" + car2.model); Serializable
  • 6. System.out.println("Creating..."); Car car = new Car("Zaz", "Forza"); car.number = "AA0001BP"; Serializable
  • 7. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); System.out.println("Serializing..."); objectOutputStream.writeObject(car); objectOutputStream.flush(); byteArrayOutputStream.flush(); objectOutputStream.close(); byteArrayOutputStream.close(); Serializable
  • 8. ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); System.out.println("Deserializing..."); Car car2 = (Car)ois.readObject(); System.out.println("car2.number=" + car2.number); System.out.println("car2.mark=" + car2.mark); System.out.println("car2.model=" + car2.model); Serializable
  • 10. Serializable. Secure private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException; private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException; private void java.io.ObjectInputStream.defaultWriteObject(java.io.ObjectOutputStream stream) throws java.io.IOException; private void java.io.ObjectInputStream.defaultReadObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException; public interface java.io.ObjectInputValidation { public void validateObject() throws InvalidObjectException; }
  • 11. Serializable. Features public class ArrayList extends AbstractList implements List, Cloneable,Serializable { private transient Object elementData[]; private int size; ... } class List implements Serializable { List next; private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("next", List.class)} };
  • 12. • Adding new fields to a class • Changing the fields from static to nonstatic • Changing the fields from transient to nontransient Serializable. Can Manage Automatically private static final long serialVersionUID = 3329999866918906824L;
  • 13. private/public/protected Object readResolve() throws ObjectStreamException private/public/protected Object writeReplace() throws ObjectStreamException Serializable. Singleton
  • 14. Serializable. Singleton public class Singleton implements Serializable { private static final long serialVersionUID = 8413502725007695828L; private static Singleton instance = null; public String name = ""; private Singleton(){}; public static Singleton getInstance(){ if (instance == null){ instance = new Singleton(); } return instance; } private Object readResolve() throws ObjectStreamException{ instance.name = this.name; return instance; } }
  • 15. Serializable. Singleton private Object readResolve() throws ObjectStreamException{ instance.name = this.name; return instance; } }
  • 16. Serializable. Singleton Singleton instance1 = Singleton.getInstance(); instance1.name = "instance1"; ............................................................................ System.out.println("Serializing..."); System.out.println("instance1.name:" + instance1.name); .............................................................................. objectOutputStream.writeObject(instance1); ............................................................................ instance1.name = "instance2"; ............................................................................ System.out.println("Deserializing..."); Singleton instance2 = (Singleton)ois.readObject(); if(instance1 == instance2){ System.out.println("instance1 == instance2"); }else{ System.out.println("instance1 != instance2"); } System.out.println("instance2.name:" + instance2.name);
  • 17. Serializable. Singleton Singleton instance1 = Singleton.getInstance(); instance1.name = "instance1"; ............................................................................ System.out.println("Serializing..."); System.out.println("instance1.name:" + instance1.name); .............................................................................. objectOutputStream.writeObject(instance1); ............................................................................ instance1.name = "instance2";
  • 18. Serializable. Singleton ............................................................................ System.out.println("Deserializing..."); Singleton instance2 = (Singleton)ois.readObject(); if(instance1 == instance2){ System.out.println("instance1 == instance2"); }else{ System.out.println("instance1 != instance2"); } System.out.println("instance2.name:" + instance2.name);
  • 20. Serializable. ENUM public enum Color { RED("red"),GREEN("green"),BLUE("blue"); private Color(String name){ this.name = name; } public String getName(){ return name; } private String name; }
  • 21. Serializable. ENUM Color red1 = Color.RED;Color green1 = Color.GREEN;Color blue1 = Color.BLUE; ..................................... System.out.println("Serializing..."); objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(red1); objectOutputStream.writeObject(green1); objectOutputStream.writeObject(blue1); ..................................... System.out.println("Deserializing..."); Color red2 = (Color)ois.readObject(); Color green2 = (Color)ois.readObject(); Color blue2 = (Color)ois.readObject(); if(red1 == red2) System.out.println("red1 == red2"); if(green1 == green2) System.out.println("green1 == green2"); if(blue1 == blue2) System.out.println("blue1 == blue2");
  • 22. Serializable. ENUM Color red1 = Color.RED; Color green1 = Color.GREEN; Color blue1 = Color.BLUE; ..................................... System.out.println("Serializing..."); objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(red1); objectOutputStream.writeObject(green1); objectOutputStream.writeObject(blue1);
  • 23. Serializable. ENUM ..................................... System.out.println("Deserializing..."); Color red2 = (Color)ois.readObject(); Color green2 = (Color)ois.readObject(); Color blue2 = (Color)ois.readObject(); if(red1 == red2) System.out.println("red1 == red2"); if(green1 == green2) System.out.println("green1 == green2"); if(blue1 == blue2) System.out.println("blue1 == blue2");
  • 24. Serializable. ENUM Serializing... Deserializing... red1 == red2 green1 == green2 blue1 == blue2
  • 26. public interface Externalizable extends java.io.Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; } Externalizable
  • 27. Externalizable. Performance public class ItemExt implements Externalizable{ private int fieldInt; private boolean fieldBoolean; private long fieldLong; private float fieldFloat; private double fieldDouble; private String fieldString; public ItemExt(){ this(0,true,0,0,0,""); } ..................................................
  • 28. Externalizable. Performance public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(fieldInt); out.writeBoolean(fieldBoolean); out.writeLong(fieldLong); out.writeFloat(fieldFloat); out.writeDouble(fieldDouble); out.writeUTF(fieldString); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { fieldInt = in.readInt(); fieldBoolean = in.readBoolean(); fieldLong = in.readLong(); fieldFloat = in.readFloat(); fieldDouble = in.readDouble(); fieldString = in.readUTF(); }
  • 29. Externalizable. Performance public abstract class ContainerExt implements Externalizable{ protected List<ItemExt> items; public ContainerExt(){ items = new LinkedList<ItemExt>(); } public void addItem(ItemExt item){ items.add(item); } .................................................. }
  • 30. /*ContainerExt1*/public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(items); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { items = (List<ItemExt>)in.readObject(); } Externalizable. Performance
  • 31. Externalizable. Performance /*ContainerExt2*/ public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(items.size()); for(Externalizable ext : items) out.writeObject(ext); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int count = in.readInt(); for(int i=0; i<count; i++){ ItemExt ext = (ItemExt)in.readObject(); items.add(ext); } }
  • 32. /*ContainerExt3*/ public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(items.size()); for(Externalizable ext : items) ext.writeExternal(out); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException{ int count = in.readInt(); for(int i=0; i<count; i++){ ItemExt ext = new ItemExt(); ext.readExternal(in); items.add(ext); } } Externalizable. Performance
  • 33. [java] Creating 100000 objects [java] Serializable: written in 971ms, readed in 1353 [java] Externalizable1: written in 1026ms, readed in 1129 [java] Externalizable2: written in 909ms, readed in 1876 [java] Externalizable3: written in 49ms, readed in 268 06/16/2013 08:24 PM 5,547,651 cont.ser 06/16/2013 08:24 PM 5,747,559 contExt1.ser 06/16/2013 08:24 PM 5,747,521 contExt2.ser 06/16/2013 08:24 PM 4,871,155 contExt3.ser Externalizable. Performance