6 Types of Java serialization framework

Source: Internet
Author: User

Here are a few common Java serialization techniques, time-consuming comparisons, Unit nanoseconds

0.002511:com.my.tools.serialize.kryoregisterserialize

0.007207:com.my.tools.serialize.fstserialize

0.00811:com.my.tools.serialize.kryoserialize

0.010137:com.my.tools.serialize.gsonserialize

0.012367:com.my.tools.serialize.fastjsonserialize

0.021474:com.my.tools.serialize.jdkserialize


1.JDKSerialize

Method One: If the student class only realizes the Serializable interface;

Method Two: If the student class only implements the Serializable interface, and also defines ReadObject (ObjectInputStream in) and WriteObject (Objectoutputsteam out);

method Three: If the student class implements the Externalnalizable interface, and the student class must implement Readexternal (ObjectInput in) and Writeexternal (ObjectOutput out) method,

public static byte[] Serialize (Object obj) {try {bytearrayoutputstream BAOs = new Bytearrayoutputstream (); O Bjectoutputstream Oos = new ObjectOutputStream (BAOs); Oos.writeobject (obj); byte[] bs = Baos.tobytearray (); Baos.close () ; Oos.close (); return BS;} catch (IOException e) {throw new RuntimeException (e);}} public static Object deserialize (byte[] bits) {try {bytearrayinputstream Bais = new Bytearrayinputstream (bits); O Bjectinputstream ois = new ObjectInputStream (bais); Object obj = Ois.readobject (); Bais.close (); Ois.close (); return obj;} catch (Exception e) {throw new RuntimeException (e);}}

2.FastjsonSerialize

one of the most basic functions involved in a JSON library is serialization and deserialization. Fastjson supports direct serialization of Java beans. Use the Com.alibaba.fastjson.JSON class for serialization and deserialization.

public static string serialize (Object obj) {string json = json.tojsonstring (obj); return json;} public static Object Deserialize (String json, class<?> clazz) {Object obj = Json.parseobject (JSON, clazz); return obj ;}

3.FSTSerialize

FST Fast-serialization is a re-implemented Java fast object serialization development package. Serialization is faster (2-10 times), smaller in size, and compatible with JDK native serialization.

Requires JDK 1.7 support.

The Java Fast Serialization library FST has been released with version 2.0, and the package name has changed to not be upgraded smoothly. In addition, the official recommendation is to use the latest version 1.58 for stability reasons.

Static Fstconfiguration configuration = Fstconfiguration. Createdefaultconfiguration (); public static byte[] Serialize (Object obj) {return Configuration.asbytearray ((Serializable) obj);} public static Object Deserialize (byte[] sec) {return Configuration.asobject (sec);}

4.GsonSerialize

This is used in JSON format and is escaped with Google Gson-2.2.4.jar.

static Gson Gson = new Gson ();p ublic static string serialize (Object obj) {string json = Gson.tojson (obj); return json;} public static Object Deserialize (String json, class<?> clazz) {Object obj = Gson.fromjson (JSON, clazz); return obj;}

5.JacksonSerialize

Jackson Library (http://jackson.codehaus.org), a Java-based open source JSON format parsing tool, contains 3 jar packages for the entire library (using the latest version 2.2):

The jackson-core.jar--core package (required) provides an API based on "stream mode" parsing.

The jackson-databind--data binding package (optional) provides APIs based on the object binding and tree model.

The jackson-annotations--annotation package (optional) provides annotation functionality.

Jackson's Advantages:

Compared to other libraries parsed by Java JSON, such as the Json-lib, Gson package, Jackson has the following advantages:

Fully functional, provide a variety of modes of JSON parsing, "object binding" easy to use, the use of annotations package can provide a lot of convenience for our development.

Performance is high, and the parsing efficiency of the "stream mode" exceeds the majority of similar JSON packages.

Core package: Jsonpaser (JSON stream read), Jsongenerator (JSON stream output).

Data binding Package: Objectmapper (build tree mode and object binding mode), Jsonnode (tree node)

public static String serialize (Object obj) {objectmapper mapper = new Objectmapper (); String json = null;try {json = mapper.writevalueasstring (obj);} catch (Exception e) {//TODO auto-generated catch BLOCKE.P Rintstacktrace ();} return JSON;} public static object Deserialize (String json, class<?> clazz) {objectmapper mapper = new Objectmapper (); Object obj = null;try {obj = Mapper.readvalue (JSON, clazz);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace () ;} return obj;}

6.KryoSerialize and Kryoregisterserialize

Kryo runs at about 20 times times the speed of Java Serializable

Kryo file size is about half of Java serializable

There are two modes of Kryo:

One is to register first (regist), then write the object, that is, the writeobject function, in fact, if you do not register first, the object will be registered, and the class assigned an ID.

Note that if it is RPC, it must be registered in the same order on both sides, otherwise an error will occur because the unique ID of the class must be clarified.

The other is to write the class name and object, that is, the Writeclassandobject function.

The Writeclassandobject function is to write (-1 + 2) (a contract number), write the class ID (first write-1, then write the class ID + class name), write the reference relationship (see the implementation of the reference), and then write the real data.

Note that the information is emptied every time the writeclassandobject is called, so there is no need to worry about an error when interacting with the client.

static kryo kryo = new kryo ();p ublic  Static byte[] serialize (object obj)  {byte[] buffer = new byte[2048];o Utput output = new output (buffer); Kryo.writeclassandobject (output, obj);byte[]  Bs = output.tobytes (); Output.close (); return bs;} Public static object deserialize (BYTE[]&NBSP;SRC)  {Input input = new  Input (src); object obj = kryo.readclassandobject (input); Input.close (); return obj;} 
static Kryo Kryo = Null;static{kryo = new Kryo (); kryo.setreferences (false); kryo.setregistrationrequired (false); Kryo.setinstantiatorstrategy (New Stdinstantiatorstrategy ());} public static byte[] Serialize (Object obj) {kryo.register (Obj.getclass ()); byte[] buffer = new Byte[2048];output Output = n EW output (buffer); Kryo.writeobject (Output, obj); byte[] bs = Output.tobytes (); Output.close (); return BS;} public static Object deserialize (byte[] src, class<?> clazz) {kryo.register (clazz); input input = new input (SRC); Obj ECT obj = kryo.readobject (input, clazz); Input.close (); return obj;}



The advantages of JSON: Clear text structure at a glance, can be cross-language, the increase in the number of attributes less impact on the parsing side. Cons: Too many bytes, depending on the different third-party class libraries.


Object Serializalbe Advantages: Java native support, do not need to provide a third-party class library, the use is relatively simple. Cons: Cannot cross-language, the number of bytes occupies relatively large, in some cases, the change of object properties is more sensitive.

When an object is serialized and deserialized, it must implement the serializable interface, but does not enforce a unique serialversionuid, declaring that the SERIALVERSIONUID has a significant effect on the upward-downward compatibility of object serialization.


We usually think that serializing a Java object into binary is faster than serializing to XML or JSON, which is actually wrong, and it is recommended to avoid Java serialization If you are concerned about performance.

6 Types of Java serialization framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.