The Persistence of Memory: Object Serialization Ch 12: “Object Streams”

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

COS 461 Fall 1997 Network Objects u first good implementation: DEC SRC Network Objects for Modula-3 u recent implementation: Java RMI (Remote Method Invocation)
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Formal Language, chapter 4, slide 1Copyright © 2007 by Adam Webber Chapter Four: DFA Applications.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
CSC 243 – Java Programming, Spring 2013 March 26, 2013 Week 8, java.lang.Clonable & java.io.Serializable Interfaces.
COP INTERMEDIATE JAVA Exception Handling Serialization.
Lab#1 (14/3/1431h) Introduction To java programming cs425
1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.
Object Serialization in Java Or: The Persistence of Memory…
Serialization, Cont’d Cerealization?. Administrivia Reminders: Swing/events quiz (group/indiv): next Mon, Feb 14 Book text, BUT ALSO try some demo programs.
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
1 Java object model Part 3: Serialization & Reflection.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Code Interview Yingcai Xiao Hari Krishna Bodicharla.
More on Inheritance Dr. Andrew Wallace PhD BEng(hons) EurIng
CIS 270—Application Development II Chapter 14—Files and Streams.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
Software Design 13.1 XML: Another TLA or the Future? XML is eXtensible Markup Language  It's a w3c standard.
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Singleton, Memento, Flyweight.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java I/O Writing and Reading Objects to File Serialization.
Serialization. Serialization is the process of converting an object into an intermediate format that can be stored (e.g. in a file or transmitted across.
Chapter 14 - Designing Data Access Classes1 Chapter 14 Designing Data Access Classes.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
Object Serialization in Java Or: The Persistence of Memory… Originally from:
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Storing Data. A Note About Creating Games Why do you want to store data? 1.Data files 2.Configuration files.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
COS 461 Recitation 7 Remote Procedure Calls. Let’s Look at Layers Again.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 11.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 15.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
COSC 1P02 Data Structures and Abstraction 2.1 Cosc 1P02 Binary Files & Persistent Objects “For myself, I am an optimist--it does not seem to be much use.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
1 Copyright © 2011 Tata Consultancy Services Limited TCS Internal.
Files and Serialization. Files Used to transfer data to and from secondary storage.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Object Writing in files
Applets In Java Visit for more Learning Resources 1.
Namespaces, Scopes, Access privileges
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy.
Client server programming
Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy.
MSIS 670: Object-Oriented Software Engineering
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Computer Science and Engineering
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Podcast Ch23f Title: Serialization
System Models Bina Ramamurthy 9/7/2019 B.Ramamurthy.
OO Java Programming Input Output.
Presentation transcript:

The Persistence of Memory: Object Serialization Ch 12: “Object Streams”

Administrivia M1 grade sheets back tonight Quiz (indiv/group): Mon, Feb 14 (happy V-day) Swing: Ch. 7 pp Event handling: Ch 8, pp Play with Swing a bit yourself Paper: Berkun, S., “How to build a better web browser.” Web essay, Dec In-class discussion, Mon Feb 21 See class homepage for URL, reading requirements

Group design followup Group 1 soln: 3/5 points Considered all important issues Stymied on actual solution Group 0 soln: 5/5 points Addressed all important issues Used available toolbox well

So you want to save your data... Common problem: You’ve built a large, complex object REVERSE INDEX Game state Database of student records Etc... Want to store to disk and retrieve later Crawl re-start Or: want to send over network to another program In general: want object persistence: outlive current program

Answer 1: Homebrew files You’ve got file I/O nailed, so... Write a set of methods for saving/loading each class that you care about public class MyClass { public void saveYourself(Writer o) throws IOException {... } public static MyClass loadYourself(Reader i) throws IOException {... } }

Coolnesses of Approach 1 Can produce arbitrary file formats Know exactly what you want to store and get back/don’t store unnecessary stuff Can build file formats to interface w/ other codes/programs XML Tab-delimited/spreadsheet Databases Etc. Nicely hierarchical data ⇒ load/save simple (conceptually & in code)

Recursive data structs

Saving recursive data public class MyClassA implements Saveable { public MyClassA(DataT dat) { // initialize private data members of A } public void saveYourself(Writer o) throws IOException { // write MyClassA identifier and private // data on output stream o o.flush(); } public static MyClassA loadYourself(Reader i) throws IOException { // parse MyClassA ID from i; fail if no A ID // parse MyClassA from the data stream i MyClassA tmp=new MyClassA(data); return tmp; }

Saving recursive data public class MyClassB implements Saveable { private MyClassA _Adat; public MyClassB(MyClassA a,DataT dat) {... } public void saveYourself(Writer o) { // write ID for MyClassB _Adat.saveYourself(o); // write other private data for B o.flush(); } public static MyClassB loadYourself(Reader i){ // parse MyClassB ID from i; fail if no B ID MyClassA tmpA=MyClassA.loadYourself(i); // parse MyClassB from the data stream i MyClassB tmpB=new MyClassB(tmpA,data); return tmpB; }

Saving recursive data public class MyClassC implements Saveable { private MyClassB _Bdat; public MyClassC(MyClassB b,DataT dat) {... } public void saveYourself(Writer o) { // write ID for MyClassC _Bdat.saveYourself(o); // write other private data for C o.flush(); } public static MyClassB loadYourself(Reader i){ // parse MyClassC ID from i; fail if no C ID MyClassB tmpB=MyClassB.loadYourself(i); // parse MyClassC from the data stream i MyClassC tmpC=new MyClassC(tmpb,data); return tmpC; }

Painfulness of Approach 1 This is recursive descent parsing/formatting You’ll use a recursive descent technique to handle the AND/OR language in M3, and elsewhere in this class But... It’s also a pain in the a** Tedious Error-prone What do you do about cyclic data structs? (A→B→A) If all you want to do is load/store data, do you need all of that infrastructure?

The object graph

Approach 2: Serialization Java provides the “serialization” mechanism Essentially does what we just walked through Automates the grunt work for you Gets complex cases right Good error trapping (version changes, etc.) Short form: public class MyClassA implements Serializable {... } public class MyClassB implements Serializable {... } public class MyClassC implements Serializable {... } // somewhere else in your code MyClassC localC=new MyClassC(...) FileOutputStream fos=new FileOutputStream(”dumpfile.obj”); ObjectOutputStream out=new ObjectOutputStream(fos); out.writeObject(localC); out.flush(); out.close();

A bit more detail... To (de-)serialize an object, it must implement Serializable All data members have to be Serializable also And so on, recursively... Primitive (atomic) types (int, char, etc.) are automatically Serializable So are Strings, arrays, most stuff in java.util, etc. This saves/restores entire object graph, including ensuring uniqueness of objects

Subtleties... static fields are not automatically serialized (why?) Not possible to automatically serialize them b/c they’re owned by an entire class, not a single object Options: final static fields are automatically initialized (once) when class is first loaded Possibly when first obj of that class is deserialized static fields initialized in static {} block also initialized when class first loaded What about other static data?

When default ain’t enough Java allows writeObject() and readObject() methods to customize output If a class overrides these methods, the serialization/deserialization mechanism calls them instead of doing the default thing They must (de-)serialize everything you care about: anything they skip doesn’t get written/loaded

writeObject in action public class DemoClass implements Serializable { private int _dat=3; private static char _sdat=’J’; public void writeObject(ObjectOutputStream o) throws IOException { o.writeInt(_dat); o.writeChar(_sdat); } private void readObject(ObjectInputStream i) throws IOException, ClassNotFoundException { _dat=i.readInt(); _sdat=i.readChar(); }

Stuff you don’t want to save Sometimes you want to not store some non- static data Computed vals that are cached just for convenience/speed Passwords or other “secret” data “Unique” IDs that are unique only w/in program scope Java has the transient keyword transient foo == “don’t save foo ” public class TDRLClass implements Serializable { public int _primary=3; // is serialized public transient int _cached=_primary*3; // _cached is _not_ serialized }

Gotchas #0 Non-serializable stuff What if class Foo has a member of class Bar, Foo is Serializable, but Bar isn’t? If you just do this: Foo f=new Foo(new Bar()); ObjectOutputStream o=new ObjectOutputStream o.writeObject(f); You get a NotSerializableException (bummer) Answer: use Foo.writeObject() / readObject() to write parts of Bar by hand. Bar must provide some way to get/set critical state