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

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

What's hot (20)

Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose world
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere Stockholm
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
droidparts
droidpartsdroidparts
droidparts
 
DynaMine: Finding Common Error Patterns by Mining Software Revision Histories
DynaMine: Finding Common Error Patterns by Mining Software Revision HistoriesDynaMine: Finding Common Error Patterns by Mining Software Revision Histories
DynaMine: Finding Common Error Patterns by Mining Software Revision Histories
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
 
Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...
Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...
Fundamentos de Akka.net para sistemas concorrentes e distribuidos usando o mo...
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and Toothpick
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Dealing with combinatorial explosions and boring tests
Dealing with combinatorial explosions and boring testsDealing with combinatorial explosions and boring tests
Dealing with combinatorial explosions and boring tests
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Java programs
Java programsJava programs
Java programs
 
Best Java Problems and Solutions
Best Java Problems and SolutionsBest Java Problems and Solutions
Best Java Problems and Solutions
 

Viewers also liked

Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Доступность веб-сайтов: WWW для всех?
Доступность веб-сайтов: WWW для всех?Доступность веб-сайтов: WWW для всех?
Доступность веб-сайтов: WWW для всех?
Ecommerce Solution Provider SysIQ
 
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Модульные сетки в реальном мире - IQLab Frontend Fusion 2012
Ecommerce Solution Provider SysIQ
 
Гибкость и Структурированность Oбъектно Oриентированноя CSS
Гибкость и Структурированность Oбъектно Oриентированноя CSSГибкость и Структурированность Oбъектно Oриентированноя CSS
Гибкость и Структурированность Oбъектно Oриентированноя CSS
Ecommerce Solution Provider SysIQ
 
Frontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and How
Ecommerce Solution Provider SysIQ
 
Психология восприятия и UX дизайн
Психология восприятия и UX дизайнПсихология восприятия и UX дизайн
Психология восприятия и UX дизайн
Ecommerce Solution Provider SysIQ
 

Viewers also liked (20)

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

Similar to Java serialization

Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
Aram Mohammed
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
Mathieu Breton
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
Raji Ghawi
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
sooryasalini
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
SpbDotNet Community
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
Richard Lord
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
ThomasHorta
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
HamletDRC
 
Spring boot
Spring boot Spring boot
Spring boot
Vinay Prajapati
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
Srinivasa Babji Josyula
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Abimbola Idowu
 

Similar to Java serialization (20)

Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Java Unit 1 Project
Java Unit 1 ProjectJava Unit 1 Project
Java Unit 1 Project
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Spring boot
Spring boot Spring boot
Spring boot
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 

More from Ecommerce Solution Provider SysIQ (14)

Developing for e commerce is important
Developing for e commerce is importantDeveloping for e commerce is important
Developing for e commerce is important
 
Magento code audit
Magento code auditMagento code audit
Magento code audit
 
Scalability and performance for e commerce
Scalability and performance for e commerceScalability and performance for e commerce
Scalability and performance for e commerce
 
non-blocking java script
non-blocking java scriptnon-blocking java script
non-blocking java script
 
Going global
Going globalGoing global
Going global
 
Going Global
Going GlobalGoing Global
Going Global
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
QA evolution, in pictures
QA evolution, in picturesQA evolution, in pictures
QA evolution, in pictures
 
Databases on Client Side
Databases on Client SideDatabases on Client Side
Databases on Client Side
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
 
Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
 
Модульные сетки в реальном мире
Модульные сетки в реальном миреМодульные сетки в реальном мире
Модульные сетки в реальном мире
 
Правила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработкеПравила хорошего SEO тона в Frontend разработке
Правила хорошего SEO тона в Frontend разработке
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
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
 
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
 
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
 
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
 
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
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
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
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
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
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
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
 
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...
 
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...
 
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
 
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...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
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
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
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...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 

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