Java Serialization

In lessons 5 and 6 of this series, you've learned how to use some of the Java
streams to read or write bytes, characters or numeric data. This lesson is about
reading or writing entire Java objects into streams.

Now consider the following scenario: a program HeadQuarterEmpProcessor
creates an instance of the object Employee. The values of its attributes
(object's state) have to be saved in a file or some other stream. Later
on, another program called BranchEmpProcessor needs to recreate the instance of
this object Employee in memory.

We could have done it by using one of the streams like DataOutputStream,
FileWriter or others. In this case both programs would need to know a format of
the saved file (data types, order of the attributes and delimiters). Luckily,
Java offers a more elegant way called object serialization, which greatly
simplifies the process of objects exchange.

To send the entire object to a stream a program can use the class
java.io.ObjectOutputStream, while the class java.io.ObjectInputStream knows how
to get an object from a stream. To serialize an object means to convert
it into a set of bytes and send it to a stream. To deserialize and object
means to read these bytes from a stream and recreate the instance of the
received object.

How to Make a Class Serializable

CIO, CTO & Developer Resources

To make a class serializable, just declare that this class implements
the interface Serializable:

Please note that we did not explicitly created an instance of the object
Employee - JVM did it for us. Make sure that definition of the class Employee is
available to JVM that reads the stream. In distributed applications it usually
runs on a remote machine.

During the process of deserialization all transient variables will be
initialized with default values according to their type, for example, integer
variables will have the value of zero.

Interface Externalizable

The method writeObject() sends all attributes of an object into a stream.
This could lead to unnecessary large object footprint, especially if you need to
serialize the values only of some of the instance variables. Java provides
Externalizable interface that gives you more control over what is being
serialized and it can produce smaller object footprint.

Externalizable interface is a subclass of Serializable.

This interface defines 2 methods: readExternal() and writeExternal() and you
have to implement these methods in the class that will be serialized (Employee).
In these methods you'll have to write code that reads/writes only the values of
the attributes you are interested in. Programs that perform serialization and
deserialization have to write and read these attributes in the same sequence.

The following class Employee2 serializes only the values of the last name and
salary.

Unlike with Serializable interface, we had to write a little more code to
implement Externalizable interface, but the size of the file NewEmployee2.ser is
only 21 bytes, whereas the file NewEmployee.ser has 207 bytes. First of all, we
serialized the values of only two attributes, and the other reason is that files
created using Externalizable interface contain data only, while files created by
default Java serialization contain class metadata that include attribute names.

The next code snippet shows you how to recreate an externalized object:

Serialization in the Real World

In some types of applications you have to write the code to serialize
objects, but in many cases serialization is performed behind the scenes by
various server-side containers. These are some of the typical uses of
serialization:

To persist data for future use.

To send data to a remote computer using such client/server Java technologies
as RMI or socket programming.

To "flatten" an object into array of bytes in memory.

To exchange data between applets and servlets.

To store user session in Web applications.

To activate/passivate enterprise java beans.

To send objects between the servers in a cluster.

When you use serialization in time-critical applications, for example
real-time stock trading systems, the size of the serialized objects should be
minimal. Keep in mind that variables with longer names produce larger footprints
during serialization, and this may substantially slow down your application.
Think of a high volume of trade orders that is being serialized. I remember
working on the application where a class TradeOrder had about a hundred member
variables. After renaming the variables into meaningless v1, v2, and so on, the
size of one TradeOrder instance was reduced by a thousand bytes. And we are
talking about serializing of thousands orders over the network!

If performance is your primary goal, use Externalizable interface instead of
Serializable. Yes, you'll have to write code to serialize each attribute, but
this may speed up serialization process substantially.

While applets can connect to a remote computer using socket or RMI
programming (these technologies will be explained in the future lessons of this
series), HTTP protocol and such Java classes as URL and URLConnection simplify
network programming. With an HTTP protocol, applets can receive or send not only
a text, but also binary objects using Java Serialization.

When an EJB container decides to passivate (unload from memory) so-called
stateful session bean, JVM persists its state in a safe place (usually on a
disk). Later on, when this bean will be activated again, all its variables will
be automatically deserialized by the EJB container.

While it may not be too difficult for JVM to convert a primitive integer
variable into four bytes for serialization, it's not as simple in case of
classes containing variables with references to other objects. The process of
converting such complex object into a sequence of bytes is called
marshalling and the process of reconstructing of the objects from these
bytes is called unmarshalling and Java does this job for you.

Even though we have not learned yet how to create Web applications, I still
want to mention that objects used for tracking of the user sessions should be
serializable, otherwise you may not be able to deploy these application in a
cluster of servers.

Java serialization is a simple but powerful feature of the language, and you
definitely will have a chance to use it in your applications.

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

If you serialize an externalizeable object, it''s readExternal or writeExternal methods will automatically get called. So, the scenario you mention should never happen. When you implement Externalizable, you take control of the serialization completely, so the transient modifier will not have an effect on fields in the Externalizable object.

Ravi04/14/04 03:19:03 PM EDT

Excellent article. I had a concern with transient data serialization when we do a serialization with externalizable interface. I mean when I implement a class with externalizable and do a normal serialization without being used its readExternal or writeExternal calls, then the Transient data is still get serialized.
Can anyone update me on this point?

Good article. As the previous comment indicates, using Java serialization can introduce some problems when the objects are read in by a different version of the software. I don''t recommend using Java serialization for ''durable'' persistence for this reason. Using Externalizable can help, but for complex applications this encourages the programmer to blend the persistence and other, unrelated aspects into the same object, which is not the best design. I would recommend delegating the Externalizable implementation into another object in this case.

Mathieu03/31/04 03:04:31 AM EST

Very Good introductory material. However I would like to add a paragraph on class version management.
Upon a change of the code of your class if you try to read an old serialized data, you may experience error. Externalize interface is for now the safe way to prevent yourself from that.

java-user03/29/04 11:15:31 AM EST

Excellent article. Liked real-world experiences shared by author.

andre03/26/04 05:01:30 PM EST

Awesome! Did not know about the alternative to Serializable which exposes your application.

For IoT to grow as quickly as analyst firms’ project, a lot is going to fall on developers to quickly bring applications to market. But the lack of a standard development platform threatens to slow growth and make application development more time consuming and costly, much like we’ve seen in the mobile space.
In his session at @ThingsExpo, Mike Weiner, Product Manager of the Omega DevCloud with KORE Telematics Inc., discussed the evolving requirements for developers as IoT matures and conducted a live demonstration of how quickly application development can happen when the need to comply wit...

SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.

The Internet of Everything (IoE) brings together people, process, data and things to make networked connections more relevant and valuable than ever before – transforming information into knowledge and knowledge into wisdom. IoE creates new capabilities, richer experiences, and unprecedented opportunities to improve business and government operations, decision making and mission support capabilities.

Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy.
How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Architect for the Internet of Things and Intelligent Systems, described how to revolutionize your archit...

MuleSoft has announced the findings of its 2015 Connectivity Benchmark Report on the adoption and business impact of APIs.
The findings suggest traditional businesses are quickly evolving into "composable enterprises" built out of hundreds of connected software services, applications and devices. Most are embracing the Internet of Things (IoT) and microservices technologies like Docker. A majority are integrating wearables, like smart watches, and more than half plan to generate revenue with APIs within the next year.

Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world.
Get ready to learn the facts:
Is there a bias against women in the tech / developer communities?
Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions?
Some beginnings of what to do about it!
In her Opening Keynote at 16th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, d...

In his keynote at 16th Cloud Expo, Rodney Rogers, CEO of Virtustream, discussed the evolution of the company from inception to its recent acquisition by EMC – including personal insights, lessons learned (and some WTF moments) along the way. Learn how Virtustream’s unique approach of combining the economics and elasticity of the consumer cloud model with proper performance, application automation and security into a platform became a breakout success with enterprise customers and a natural fit for the EMC Federation.

The Internet of Things is not only adding billions of sensors and billions of terabytes to the Internet. It is also forcing a fundamental change in the way we envision Information Technology. For the first time, more data is being created by devices at the edge of the Internet rather than from centralized systems. What does this mean for today's IT professional?
In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists addressed this very serious issue of profound change in the industry.

Discussions about cloud computing are evolving into discussions about enterprise IT in general. As enterprises increasingly migrate toward their own unique clouds, new issues such as the use of containers and microservices emerge to keep things interesting.
In this Power Panel at 16th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the state of cloud computing today, and what enterprise IT professionals need to know about how the latest topics and trends affect their organization.

It is one thing to build single industrial IoT applications, but what will it take to build the Smart Cities and truly society-changing applications of the future? The technology won’t be the problem, it will be the number of parties that need to work together and be aligned in their motivation to succeed.
In his session at @ThingsExpo, Jason Mondanaro, Director, Product Management at Metanga, discussed how you can plan to cooperate, partner, and form lasting all-star teams to change the world and it starts with business models and monetization strategies.

Converging digital disruptions is creating a major sea change - Cisco calls this the Internet of Everything (IoE). IoE is the network connection of People, Process, Data and Things, fueled by Cloud, Mobile, Social, Analytics and Security, and it represents a $19Trillion value-at-stake over the next 10 years.
In her keynote at @ThingsExpo, Manjula Talreja, VP of Cisco Consulting Services, discussed IoE and the enormous opportunities it provides to public and private firms alike. She will share what businesses must do to thrive in the IoE economy, citing examples from several industry sectors.

There will be 150 billion connected devices by 2020. New digital businesses have already disrupted value chains across every industry. APIs are at the center of the digital business. You need to understand what assets you have that can be exposed digitally, what their digital value chain is, and how to create an effective business model around that value chain to compete in this economy. No enterprise can be complacent and not engage in the digital economy. Learn how to be the disruptor and not the disruptee.

Akana has released Envision, an enhanced API analytics platform that helps enterprises mine critical insights across their digital eco-systems, understand their customers and partners and offer value-added personalized services.
“In today’s digital economy, data-driven insights are proving to be a key differentiator for businesses. Understanding the data that is being tunneled through their APIs and how it can be used to optimize their business and operations is of paramount importance,” said Alistair Farquharson, CTO of Akana.

Business as usual for IT is evolving into a "Make or Buy" decision on a service-by-service conversation with input from the LOBs. How does your organization move forward with cloud? In his general session at 16th Cloud Expo, Paul Maravei, Regional Sales Manager, Hybrid Cloud and Managed Services at Cisco, discusses how Cisco and its partners offer a market-leading portfolio and ecosystem of cloud infrastructure and application services that allow you to uniquely and securely combine cloud business applications and services across multiple cloud delivery models.

The enterprise market will drive IoT device adoption over the next five years.
In his session at @ThingsExpo, John Greenough, an analyst at BI Intelligence, division of Business Insider, analyzed how companies will adopt IoT products and the associated cost of adopting those products.
John Greenough is the lead analyst covering the Internet of Things for BI Intelligence- Business Insider’s paid research service. Numerous IoT companies have cited his analysis of the IoT. Prior to joining BI Intelligence, he worked analyzing bank technology for Corporate Insight and The Clearing House Payment...

"Optimal Design is a technology integration and product development firm that specializes in connecting devices to the cloud," stated Joe Wascow, Co-Founder & CMO of Optimal Design, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.

SYS-CON Events announced today that CommVault has been named “Bronze Sponsor” of SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. A singular vision – a belief in a better way to address current and future data management needs – guides CommVault in the development of Singular Information Management® solutions for high-performance data protection, universal availability and simplified management of data on complex storage networks. CommVault's exclusive single-platform architecture gives companies unp...

Electric Cloud and Arynga have announced a product integration partnership that will bring Continuous Delivery solutions to the automotive Internet-of-Things (IoT) market. The joint solution will help automotive manufacturers, OEMs and system integrators adopt DevOps automation and Continuous Delivery practices that reduce software build and release cycle times within the complex and specific parameters of embedded and IoT software systems.

"ciqada is a combined platform of hardware modules and server products that lets people take their existing devices or new devices and lets them be accessible over the Internet for their users," noted Geoff Engelstein of ciqada, a division of Mars International, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.

Internet of Things is moving from being a hype to a reality. Experts estimate that internet connected cars will grow to 152 million, while over 100 million internet connected wireless light bulbs and lamps will be operational by 2020. These and many other intriguing statistics highlight the importance of Internet powered devices and how market penetration is going to multiply many times over in the next few years.

JavaScript is primarily a client-based dynamic scripting language most commonly used within web browsers as client-side scripts to interact with the user, browser, and communicate asynchronously to servers.
If you have been part of any web-based development, odds are you have worked with JavaScript in one form or another. In this article, I'll focus on the aspects of JavaScript that are relevant within the Node.js environment.

The Internet of Things (IoT) has quickly become the next “be all to end all” in information technology. Touted as how cloud computing will connect everyday things together, it is also feared as the real- life instantiation of The Terminator’s Skynet, where sentient robot team with an omnipresent and all-knowing entity that uses technology to control, and ultimately destroy, all of humanity.

We Need a Holistic Network Infrastructure: Why Controllers Are Not Cutting It
For years, we've relied too heavily on individual network functions or simplistic cloud controllers. However, they are no longer enough for today's modern cloud data center. Businesses need a comprehensive platform architecture in order to deliver a complete networking suite for IoT environment based on OpenStack.
In his session at @ThingsExpo, Dhiraj Sehgal from PLUMgrid discussed what a holistic networking solution should really entail, and how to build a complete platform that is scalable, secure, agile and auto...

Digital Transformation is the process of updating your business and IT infrastructure to align with today's and tomorrow's consumers. Today that is important, but hard to do. Mobile consumer behaviors are changing far faster than most IT budgets and initiatives and that can cause problems. If your customers are adopting technologies and changing their path-to-purchase journeys at a pace that is faster than you can deliver, then you are opening up an opportunity gap for a more nimble competitor.

The multi-trillion economic opportunity around the "Internet of Things" (IoT) is emerging as the hottest topic for investors in 2015. As we connect the physical world with information technology, data from actions, processes and the environment can increase sales, improve efficiencies, automate daily activities and minimize risk.
In his session at @ThingsExpo, Ed Maguire, Senior Analyst at CLSA Americas, will describe what is new and different about IoT, explore financial, technological and real-world impact across consumer and business use cases. Why now?
Significant corporate and venture...

Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more.
In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, examineed the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps still in...

What if, during a snow emergency, an on-the-ground sensor could automatically trigger a relevant emergency notification related to snowfall and road impact. And then, after it’s triggered, that notification is delivered intelligently to individuals based on an extensive set of rules designed to alert the most available and capable responders.
This “what if” question about “smart highways” is short-sighted. We are already there, and we are only getting started. While mainstream attention is paid to machine-to-machine communications, new technologies are being developed to make these communica...

WebRTC: together these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems.
In his session at WebRTC Summit, Cary Bran, VP of Innovation and New Ventures at Plantronics and PLT Labs, will provide an overview of this technological shift, including associated business and consumer communications impacts, and opportunities it may enable, complement or entirely transform.

As organizations realize the scope of the Internet of Things, gaining key insights from Big Data, through the use of advanced analytics, becomes crucial. However, IoT also creates the need for petabyte scale storage of data from millions of devices. A new type of Storage is required which seamlessly integrates robust data analytics with massive scale. These storage systems will act as “smart systems” provide in-place analytics that speed discovery and enable businesses to quickly derive meaningful and actionable insights.
In his session at @ThingsExpo, Paul Turner, Chief Marketing Officer at...

A recent purchase of mine was a 2015 Jeep. Until now, I thought it was a safe and reliable car, but that is not the case anymore. As technology advances and cars become smarter and more technologically savvy, they become another target for hackers.
Imagine speeding down the highway, zooming past 18-wheelers, SUVs and coupes, when all of a sudden, your brakes give out and your speed increases. Instantly, you think what could be wrong with the car, you pump your breaks and check your dash and there is no sign of stopping. Instant panic washes over you and a fear of dread drowns out the honkin...

In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway.
But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years.
This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles.
But adding sensors and wireless connectivity won't work in environments that demand unwavering reliability and performance.
In his session at @ThingsExpo, Ron Sege, CEO of Echelon, discussed how as enterprise IT embraces other IoT-related technology trends, enterprises with in...

As much as I like to promote and evangelize mobile technologies and mobile commerce, it remains in its infancy.
My preliminary research reveals it is critical for a mobile retailer to know who is using a mobile application in order to maximize sales. This knowledge should then be used to present a customized mobile experience based upon the user's preferences and demographics. Even though consumers uniformly don't like the "idea" of vendors collecting data on them, they are happy to give it up in exchange for special treatment, discounts and deals as demonstrated by the high numbers of loy...

The concept behind the Internet of Things has been around for a while now, ATMs being some of the first enterprise, hardened, network-connected, managed devices for mainstream consumer use. So too with our mobile phones, these are not new concepts to network technicians or hardware geeks. But for the rest of us, we simply never imagined the extents that the "ubiquity of connectedness" would take all other industries, from biotech to automotive, personal care to agriculture, entertainment to custom manufacturing. The list is as long as our imaginations.

Business and IT leaders today need better application delivery capabilities to support critical new innovation. But how often do you hear objections to improving application delivery like, "I can harden it against attack, but not on this timeline"; "I can make it better, but it will cost more"; "I can deliver faster, but not with these specs"; or "I can stay strong on cost control, but quality will suffer"? In the new application economy, these tradeoffs are no longer acceptable. Customers will abandon your brand forever for a slow response or a privacy breach; competitors will steal critical ...

"PLUMgrid is a software defined networking company - we provide virtual network infrastructure which plugs into any framework you're using," explained Dhiraj Sehgal of PLUMgrid in this SYS-CON.tv interview at Cloud Expo (http://www.CloudComputingExpo.com), held June 9-11, 2015, at the Javits Center in New York City.

Cloud computing budgets worldwide are reaching into the hundreds of billions of dollars, and no organization can survive long without some sort of cloud migration strategy. Each month brings new announcements, use cases, and success stories.