Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Comparing the serialization and deserialization of Java Objects

This article compares standard Java binary serialization against the serialization of JavaBeans in XML and inside a MySQL database

The Java programming language is strongly based on the concepts defined in the object-oriented paradigm. This means that it is common to manipulate fields, methods, variables, and other elements through class instances, which are stored in variables that access the class’s features.

The manipulation of objects in Java uses the memory for variable storage while the application is running. However, there are several situations when it is required to serialize the object, i.e. store them in another location other than the memory in order to later access them and store them back in memory.

This store operation in locations other than the memory is called serialization. The inverse operation, i.e. reading and subsequent placement of objects in memory, is called deserialization. Nowadays there are several techniques, patterns, libraries, frameworks and solutions to help Java developers serialize and deserialize the objects in a simple and fast fashion that allow several additional features beyond the storage.

This article presents a technical comparison between approaches that allow serialization of Java objects into binary files and with the XML format that store the object on a file inside the computer's file system. The article also compares these two storage modes with the binary serialization of objects inside a relational database. The comparison evaluates the time spent on serialization/deserialization, the features available for each approach and technical details required when you need to make a decision regarding the available choices to persist Java objects. With the information presented in this article the reader will get an overview of how to implement serialization and deserialization of simple objects in files and inside a database.

Now we will see the serialization and deserialization concepts, the details of the testing environment, and the data set used for the comparison between the approaches.

Data serialization and deserialization

Before the discussion of the technical details involved in object serialization in Java, it is important to know which are the main scenarios for using this feature and what are the gains when using it. The main applications for serialization/deserialization are: interoperability, cache servers, object-relational mapping, state persistence in games and collaborative applications.

When we create an objects we have an element of the programming language that have behavior, represented by its methods, and characteristics, represented by fields that are usually accessed through public methods know as getters and setters. The object’s characteristics store data according to existing data types in Java and also according to the types of data created by the user. In many situations the developer has to have a way to exchange data between heterogeneous applications (not developed in Java) or homogeneous (developed on the Java platform). This interoperability aspect is one of the main reasons for the persistence of Java objects through serialization/deserialization. For instance, an external financial system may require that, at a certain time, all the data stored inside the Java objects are sent to external audit software. Another example includes the communication through components (such as Web Services) that requires some kind of serialization/deserialization of objects to exchange information between different systems with open protocols like SOAP.

Nowadays cache servers, such as Memcached, are being broadly deployed to speed up Web applications. The purpose of these servers is to use caching techniques to fasten the access to objects already created. The use of serialization/deserialization in this scenario plays an important role as the core of these servers depends directly on how serialization/deserialization is implemented.

Another well known example of serialization is found on applications that map Java class models on database models. The implementation and use of this mapping is known by the acronym ORM (Object-Relational Mapping) and its implementation is facilitated by frameworks like Hibernate and Spring. These frameworks use the concepts of serialization/deserialization internally in order to encapsulate the details involved in the information persistence.

The use of serialization and deserialization in games is perhaps the clearest example of the application of this feature. In video games there is a story that must be followed by the character during several hours of gameplay. In this context most games provide the save and load option that stops the game in order to continue it at another appropriate time.

Saving the game state can be done by the user or automatically (auto-save), where at specific times (after the defeat of a boss level, for example) the mechanism automatically saves the player's progress. Here the act of saving is implemented as the serialization of all the objects that make up the state of the player (items in the backpack, points, elapsed time) and the level (enemies eliminated, changes in the elements of the scenario, open doors). The deserialization is performed manually when the user loads a saved game or automatically when the character dies or performs an action in the game that cannot be undone because it is required for the history’s progress (eliminating the princess to be rescued, for example).

The object’s serialization/deserialization is also used in video games when they support more than one player, i.e. multiplayer. This setting requires the serialization of objects that store specific information such as the position of the player, their stats and other vital information. The serialized object is then transmitted via the network to a server that will forward it to the other participants of the same game. The entire process of serialization/network transmission/deserialization should be as fast as possible so that all participants have a sense of presence and immersion on the virtual environment.

The same serialization process used in multiplayer games is also employed in remote synchronous collaborative applications. This type of application allows more than one person to work together with a team to perform some kind of work collaboratively. For example, collaborative modeling sessions of a UML diagram. In this type of collaboration one or more participants use a CASE tool to create together the elements of the diagram. To ensure the correct data visualization between all participants is necessary to perform the steps serialization/network transmission/deserialization when every change happens in the model in order to propagate to all elements participating in the modifications.

The steps to serialize an object in Java are not complex when using the platform provided serialization mechanisms. Considering the programming aspect, a class should implements an empty interface called Serializable in order to be serialized. This interface has no content and it notifies the virtual machine that its Java objects can be serialized. Most objects serialized are basically POJOs (Plain Old Java Objects) that contains data that implement the Serializable interface so that it can be serialized/deserialized.

In order to serialize an object the developer have develop a way to store an object identifier and the values of all the public fields so that this object can be recreated in the deserialization process. A major limitation of the serialization happens when there are dependencies between objects, such as associations and aggregations. This limitation occurs because one or more fields of a class have the data types of other classes. In such scenarios the serialization mechanism must serialize all the other linked objects.

In addition to speed up the serialization/deserialization of objects, the developer must also take other factors into consideration when evaluating the serialization mechanisms. Factors such as size of the serialized object, interoperability, security, compression, encryption, and others can make the implementation easier or harder. Therefore, in order to help the developer choose how to work with serialization this article will present a comparison between the standard Java binary serialization, the XML serialization used in Java Beans, and the binary serialization using a MySQL database. The next section presents the characteristics of the test environment and how the data set was generated to perform the comparison of the approaches.

Test environment and methodology

The test environment chosen to compare the three serialization/deserialization approaches featured a desktop computer equipped with the Intel Core i7 950 microprocessor which contains four cores (8 cores seen by the operating system due to Intel’s Hyper Threading technology), running at 3.06 GHz each, 12 GB of DDR3 RAM, a 64 KB L1 cache, a 256 KB L2 cache and a 8 MB L3 cache. This computer also had a 1TB SATA 2 HD whose theoretical maximum data transfer rate is approximately 300 MB/s. The operating system was a 64 bit Windows 2008 R2 Enterprise with SP1 running in a real (non-virtualized) installation with a MySQL 5.5 and a Java 2 SE 1.6.0_26 version. The OS file system chosen was a single NTFS partition.

The MySQL database was chosen for testing because it showed the best results while reading and writing when using the tables set with the MyISAM engine. The other databases evaluated were SQL Server 2008, Oracle 11g, and PostgreSQL 9.1.

When comparing the data recording through the three chosen approaches (binary serialization, XML and database) one need to consider a simple POJO. Therefore, all the tests used a new custom object with fields that contain the most used Java data types: Integer , UUID ( Universal Unique Identifier) , String , Date , Long , Float , Double , Boolean, and a 1024 byte array. Listing 1 shows the source code of MyObjectToSerialize class that implement the Serializable interface required for the serialization and deserialization of objects. In addition, the class contains private fields with internal variables, public getters and setters methods, the default constructor without parameters (in compliance with the Java Bean standard), and the static method called getMyObjectToSerialize() which takes as parameters the values of the fields and returns an object.

Listing 1. Contents of the MyObjectToSerialize.java file

import java.util.*;
import java.io.Serializable;
 
// You must implement the empty Serializable interface 
// to be able to serialize/deserialize objects of this class
public class MyObjectToSerialize implements Serializable 
{
	
// Private fields with the most common Java datatypes
	private int fInt;
	private String fString;
	private byte[] fByte;
	private Date fDate;
	private String fUUID;
	private Long fLong;
	private Float fFloat;
	private Double fDouble;
	private Boolean fBoll;

   // Empty constructor as recommended bu the Java Bean standard
    public  MyObjectToSerialize() 
    {
    }

    // This method receive the values and returns a MyObjectToSerialize instance
    public static MyObjectToSerialize getMyObjectToSerialize(int fI, String fS, byte[] fB, Date fD, String fU, Long fL, Float fF, Double fDo, Boolean fBo) 
    {
    	MyObjectToSerialize o = new MyObjectToSerialize();

	o.setFInt(fI);
	o.setFString(fS);
	o.setFByte(fB);
	o.setFDate(fD);
	o.setFUUID(fU);
	o.setFLong(fL);
	o.setFFloat(fF);
	o.setFDouble(fDo);
	o.setFBoll(fBo);

    	return o;

    }

       // From now on we have the getters and setters for each private field
	public int getFInt() {
		return fInt;
	}

	public void setFInt(int id) {
		fInt = id;
	}

	public String getFString() {
		return fString;
	}

	public void setFString(String fString) {
		this.fString = fString;
	}

	public byte[] getFByte() {
		return fByte;
	}

	public void setFByte(byte[] fByte) {
		this.fByte = fByte;
	}

	public Date getFDate() {
		return fDate;
	}

	public void setFDate(Date fDate) {
		this.fDate = fDate;
	}

	public String getFUUID() {
		return fUUID;
	}

	public void setFUUID(String fUUID) {
		this.fUUID = fUUID;
	}

	public Long getFLong() {
		return fLong;
	}

	public void setFLong(Long fLong) {
		this.fLong = fLong;
	}

	public Float getFFloat() {
		return fFloat;
	}

	public void setFFloat(Float fFloat) {
		this.fFloat = fFloat;
	}

	public Double getFDouble() {
		return fDouble;
	}

	public void setFDouble(Double fDouble) {
		this.fDouble = fDouble;
	}

	public Boolean getFBoll() {
		return fBoll;
	}

	public void setFBoll(Boolean fBoll) {
		this.fBoll = fBoll;
	}

}

The POJO in Listing 1 contains the object which we will use in the serialization/deserialization tests. We also need to create multiple objects with random values for the POJO’s fields since the test will check the serialization and deserialization performance. Since the goal is to compare the performance for three persistence approaches, we chose to create very simple tests. In real world scenarios it is likely that the values obtained can be different. Nevertheless, the tests can serve as a starting point for evaluating the serialization approaches discussed in this article and can be used as an argument for more investment in this area. The readers who are interested only in binary serialization can check the references section for a link to a project that compares the performance of more than 20 possible binary and XML serialization in Java. However, this project only takes into account the execution times and does not test serialization into databases.

The dataset for the tests is 1,000 object of the MyObjectToSerialize class whose values for each field were generated randomly. To assemble the test dataset we used the binary serialization format, but for each approach this initial dataset was used on to initialize the process.

A class called RandomValues was created to generate the files that are part of the test suite. The commented source code of this class is in the RandomValues.java file and is shown in Listing 2.

Listing 2. The RandomValues.java file that contains the process to generate the set of MyObjectToSerialize objects

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public final class RandomValues
{

/ / The AB field is used to indicate which characters can be used
/ / to create a random value for the String data type
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/ / The variable rnd will be used to generate random values for many datatypes
static Random rnd = new Random();

/ / The following method returns a random string with the size 
// of the len parameters and based on the characters of the private field AB
String randomString( int len ) 
{
   StringBuilder sb = new StringBuilder( len );
   for( int i = 0; i < len; i++ ) 
      sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
   return sb.toString();
}

// This method perform the default binary serialization of Java
// for the object in the first parameter
// and place the contents in the file location specified in the second parameter

private static void saveObject(Serializable object, String filename)
            throws IOException {
        ObjectOutputStream objstream = new ObjectOutputStream(
                new FileOutputStream(filename));
        objstream.writeObject(object);
        objstream.close();
    }

   
   public static void main(String[] args) 
   {
		int qtdObjs;
		String path;

// Here we handle two parameters: the amount of objects 
// and the ser/des approach
// Checking the parameters
		if(args.length!=2)
		{
			System.out.println("Use: RandomValues qtd path");
			return;
   		}

   		try
		{ 
			qtdObjs =	Integer.valueOf(args[0]).intValue();
		}
		catch (NumberFormatException ex)
		{
		   System.out.println("Number of objects is invalid!");  
		   return;
		}

		path = args[1];

	   	// A RandomValues object that will generate the random values
		RandomValues r = new RandomValues();

		// Main loop to create all the objects
		for( int i = 0; i < qtdObjs; i++ ) 
		{
			
			// A new random integer
			int fI = rnd.nextInt();

			// A new 50 lenght String
			String fS = r.randomString(50);

			// Creating 1024 random de byte values
			byte[] fB = new byte[1024];
			rnd.nextBytes(fB);

			// A new random Date value
			Date d = new Date(rnd.nextLong());
	        
			// A new random UUID value
			String uuid = UUID.randomUUID().toString();

			// A new random Long value
			Long fL = rnd.nextLong();
			
			// A new random Float value
			Float fF = rnd.nextFloat();

			// A new random Double value
			Double fDo =  rnd.nextDouble();

			// A new random Boolean value
			Boolean fBo = rnd.nextBoolean();

			// Create the MyObjectToSerialize with all the prévios
// random values for the fields
			MyObjectToSerialize m = new MyObjectToSerialize();

			m= 
MyObjectToSerialize.getMyObjectToSerialize(fI,fS,fB,d,uuid,fL,fF,fDo,fBo);

	        try 
	        {
// Serializes the object with the binary format and the file name
// at the selected folder
// The variable i is the main loop counter
			saveObject(m, path + "/object" + i + ".ser");

	        } catch (Exception e) 
	        {
	            e.printStackTrace();
	        }
		}


   }

}

The main method of the RandomValues class takes two parameters that must be set when the program is called from the console: the number of objects to be generated and the storage location of the binary files. Then the method stores the parameter values in variables and initializes a loop to generate the objects. Inside the loop variables the data types Integer, String, byte array, Date, Long, Float, Double, and Boolean are created and receive random values by the methods of the Random class, represented by rnd object. Finally, the MyObjectToSerialize object is created from the static method getMyObjectToSerialize and this object is serialized in binary form by the SaveObject method, which makes use of the ObjectOutputStream and FileOutputStream classes.

Once the POJO and the class that generates the tests were defined we must implement how the performance measurement will be performed. There are many tools in and techniques that can be used to instrument the code and measure their execution time, such as the tools include JAMon, Visual JM, JProbe and the JavaMelody. However, to measuring the performance of serialization/ deserialization in this article we chose to create a timer similar to a class, called Stopwatch, whose source code was stored in Stopwatch.java file shown in Listing 3. We opted for a custom class to make the test simpler and easier to understand.

Listing 3. The Stopwatch.java file that contain the class responsible to perform the running time measurement

import java.text.SimpleDateFormat;  
import java.util.Calendar;    
  
// This class perform time measurements for the performance tests
// Its contents are based on the Stopwatch class produced by Carlos Quintanilla
// and available at: http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html
public class Stopwatch {  
   
   // Time constants
    private final long nsPerTick = 100;  
    private final long nsPerMs = 1000000;  
    private final long nsPerSs = 1000000000;  
  
    // Variables to store the time and control the watch
    private long startTime = 0;  
    private long stopTime = 0;  
    private boolean running = false;  
      
    // Starting the time interval measurement
    public void start() {  
        this.startTime = System.nanoTime();         
        this.running = true;  
    }  
      
     // Stoping the time interval measurement  
    public void stop() {  
        this.stopTime = System.nanoTime();  
        this.running = false;  
    }  
      
     // Restarting the time interval measurement
    public void reset() {  
        this.startTime = 0;  
        this.stopTime = 0;  
        this.running = false;  
    }  
      
    // Get the time in nanoseconds 
    // 1 Tick = 100 nanoseconds 
    public long getElapsedTicks() {  
        long elapsed;  
        if (running) {  
             elapsed = (System.nanoTime() - startTime);  
        }  
        else {  
            elapsed = (stopTime - startTime);  
        }  
        return elapsed / nsPerTick;  
    }  
      
   
    // Get the time in the following formart: 
    // 00:00:00.0000000 
    public String getElapsed() {  
        String timeFormatted = "";  
        timeFormatted = this.formatTime(this.getElapsedTicks());          
        return timeFormatted;  
    }  
      
    // Format the time as 00:00:00.0000000 
    private String formatTime(final long elapsedTicks) {          
        String formattedTime = "";  
      
        SimpleDateFormat formatter = new SimpleDateFormat("00:mm:ss.SSS");  
        Calendar calendar = Calendar.getInstance();          
          
        if (elapsedTicks <= 9999) {  
            calendar.setTimeInMillis(0);  
            formattedTime = formatter.format(calendar.getTime())   
                    + String.valueOf(String.format("%04d", elapsedTicks));  
        }  
        else {  
            calendar.setTimeInMillis(elapsedTicks * nsPerTick / nsPerMs);              
            String formattedTicks = String.format("%07d", elapsedTicks);  
            formattedTicks = formattedTicks.substring(formattedTicks.length() - 4);  
            formattedTime = formatter.format(calendar.getTime()) + formattedTicks;  
        }  
        return formattedTime;  
    }  
} 

This class begins by defining some constants used to convert measurement periods. Then variables of type Long are created to store the start time, pause and resume control inside the methods start(), stop() and reset(). Since the start() method begin the time counting using the nanoTime() method of the System class we should perform a time conversion to transform in nanoseconds into seconds. This conversion is performed by the getElapsedTicks () method which uses the equivalence of 1 Tick = 100 nanoseconds. The time is then returned by the getElapsed() method which, in turn, calls formatTime () to actually format the time in a user friendly string that show the hour, minute, second, millisecond and ticks elapsed.

We chose to create a new class called ObjectSerDes to perform the serialization and deserialization tests. This class receives five parameters when called from the console:

  • The first parameter indicates what action should be performed. If the letter S is provided a serialization test will be performed and if the letter D is typed a deserialization test will happen;
  • The second parameter is used to specify which type of approach that will be used in the tests. The possible values for this parameter are: FS, XML and MySQL for the test execution using binary files stored in File System (files), XML format or inside a MySQL database, respectively;
  • The third parameter is the the number of objects that will be created for the test. As previously mentioned, the comparison of the approaches use 1,000 objects;
  • The fourth parameter is the number of times that the same test will be repeated. This repetition is very important because it is possible to obtain statistical values such as mean, standard deviation, median, and mode that identify trends and provide statistical confidence for the tests’ results;
  • The fifth and last parameter is the path that contains the files generated by RandomValues class previously discussed in this section. This set of files has to be the same for each test performed with the three approaches to ensure that we are comparing the same data across the approaches. These objects are initially serialized in binary format; however each test will measure the serialization/deserialization chosen by the second parameter value.

The file that performs the tests was named ObjectSerDes.java and its partial content is shown in Listing 3.

Listing 3. Partial contents of the file ObjectSerDes.java which performs tests for serialization and deserialization

import java.sql.*;
import java.util.*;
import java.io.*;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;

public class ObjectSerDes 
{
    public static void main(String[] args) 
    {
        
	 // FIRST PART: PARAM CAPTURE/HANDLING 
        int MAX_OBJS = 0;
        int MAX_TESTS = 0;

        String op;
        String path;
        String method;

// Here we get the five parameters:
// 1) Serialization or deserialization (S or d)
// 2) The approach used (FS,XML or MySQL)
// 3) The amount of objects
// 4) The number of test repetitions
// 5) The path with the files

        // Parameter Checks
        if(args.length!=5)
        {
            System.out.println("Use: ObjectSerDes {S,D} {FS,XML,MySQL } qtd_objects qtd_tests path");
            return;
        }

        op = args[0];
        method = args[1];

        try
        { 
            MAX_OBJS  = Integer.valueOf(args[2]).intValue();
            MAX_TESTS = Integer.valueOf(args[3]).intValue();
        }
        catch (NumberFormatException ex)
        {
           System.out.println("Something wrong with the numeric values!");  
           return;
        }

        path = args[4];

	// SECOND PART: TEST EXECUTION
        try {
            
   	     MyObjectToSerialize[] objs = new MyObjectToSerialize[MAX_OBJS];
            Stopwatch timer = new Stopwatch();  
            Connection conn = null;

    // Deserialization tests
            if(op.equals("D"))
            {
                for( int cont = 0; cont < MAX_TESTS; cont++ ) 
                {

                    if(method.equals("FS"))
                    {
                        timer.start();     
                        
                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            objs[i] = (MyObjectToSerialize) loadObject(path + "/object" + i + ".ser");
                        
                        timer.stop();  
                    }

                    if(method.equals("XML"))
                    {
                        timer.start();     
                        
                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            objs[i] = (MyObjectToSerialize) loadObjectXML(path + "/Ser_object" + i + ".xml");

                        timer.stop();  
                    }

                    if(method.equals("MySQL"))
                    {
                        conn = getConnectionMySQL();

                        timer.start();     
                        
                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            objs[i] = (MyObjectToSerialize) loadObjectDB(conn,i);

                        timer.stop();  
                    }

                    
                    System.out.println("Test " + method +  " Deserialize " + cont + " (N=" + MAX_OBJS +") - Time:" + timer.getElapsed());  
                }
            }
     else // Serialization tests

            {
                
                // Get the object to serialize!
                for( int i = 0; i < MAX_OBJS; i++ ) 
                        objs[i] = (MyObjectToSerialize) loadObject(path + "/object" + i + ".ser");
                
                // Starting the tests
                for( int cont = 0; cont < MAX_TESTS; cont++ ) 
                {
                    
                    if(method.equals("FS"))
                    {
                        timer.start();     
                        
                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            saveObject(objs[i], path + "/Ser_object" + i + ".ser");
                        
                        timer.stop();  
                    }

                    if(method.equals("XML"))
                    {
                        timer.start();     

                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            saveObjectXML(objs[i], path + "/Ser_object" + i + ".xml");
                        
                        timer.stop();  
                    }

                    if(method.equals("MySQL"))
                    {
                        conn = getConnectionMySQL();
                        cleanDB(conn);

                        timer.start();     
                        
                        for( int i = 0; i < MAX_OBJS; i++ ) 
                            saveObjectDB(objs[i],conn,i);
                        
                        timer.stop();  
                    }

                System.out.println("Test " + method + " Serialize " + cont + " (N=" + MAX_OBJS +") - Time:" + timer.getElapsed());  
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The ObjectSerDes class, shown in Listing 3, is incomplete because it only contains the main() method. The next sections of this article will describe the missing methods guided by the explanation of each approach used for serialization/deserialization of objects. The tests with binary serialization to the file system require the SaveObject() and loadObject() methods. The tests with XML serialization require the saveObjectXML() and loadObjectXML(). The tests with serialization in MySQL you must have the getBytes(), getConnectionMySQL(), cleanDB(), saveObjectDB() and loadObjectDB() methods.

The main() method of the ObjectSerDes class was divided into two parts: the first part handles the five parameters that the program requires to run: action, serialization/deserialization approach, number of objects, number of repetitions and path in the variables op, method, MAX_OBJS, and MAX_TEST, respectively. For instance, to perform 50 serialization tests using MySQL with 1,000 objects stored on the files at c:\TestsSer path the following command line must be typed on the operating system console: java ObjectSerDes S MySQL 1000 50 c:\TestsSer.

The second part of the main() method begins with a try/catch block that will be used to handle any exceptions that may occur during all tests. Shortly after the beginning of this block an array of objects of the MyObjectToSerailize class (the POJO) is created with the number of elements equal to the number of objects displayed in the third parameter. This array will be used to initialize values as we shall see later. Other objects are also created to store the time (the Stopwatch class) and to store the connection with the database (Connection class).

The next lines of the program check which the action will be performed in the test through the contents of the variable op. If it contains the D value a deserialization tests will be executed and if the value stored is S serialization tests will be done.

If the user action chosen is serialization, the objs array is filled with the values of objects already serialized and generated by the auxiliary program RandomValues that creates many files with objects serialized. This filling is done through a simple loop that deserializes objects on the loadObject() method without computing its running time, since the option chosen by the user was to test the serialization. The storage of objects in the objs array is just a necessary step for the initialization of the serialization tests and not part of the test itself.

Inside the if or else blocks corresponding to the serialization or deserialization actions there is a verification of the method variable to see what value (FS, MySQL or XML) represents the approach being tested.

Finally, when the loop that performs the testing is completed a message is printed indicating how long it took to perform the operation according to the provided test parameters.

After the creation of the POJO and the classes that generates the tests, do the measurement of the execution time and perform the tests we can begin to run the serialization and deserialization tests for each of the three approaches.

Conclusion

Class instantiation through objects is one of the main elements that characterize the Java programming language. It is common to apply the operation known as serialization and its counterpart, the deserialization, in applications that need to persist Java objects in another location other than the memory. Nowadays there are some libraries, frameworks, tools and solutions that can be used to fulfill this goal.

This article presents the serialization and deserialization concepts along with examples where they are employed. The article also described the test environment used and how a POJO was created to receive a data set.



Mauro Pichiliani has the Master of Science degree on collaborative systems by the Aeronatics Institute of Technology (ITA) in Brazil. He is a specialist on database technologies with more than 8 years of experience on the industry...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login