A high-performance fast deep copy method for Java. Cloneable?

Source: Internet
Author: User
Tags shallow copy



When I design the database cache layer, I need to make a deep copy of the data so that the data objects that the user operates are not shared.



This idea is actually similar to Erlang, which is to solve concurrency problems with data not sharing.





1. Serialization?


The original approach was to serialize, I used the JSON serialization, Lib-json. A more traditional approach. Serializes the data field into JSON save. When it is removed, it is deserialized.



Test 100 data, 100 cycles, even the TM took 15 seconds.



What's the concept of this? It's horrible.



So online search, find a Jackson, known as the performance of XXX, than Google's Gson high xxx.



After replacement, the speed drops to 3700ms. Well. That's a bit of a meaning.



But only 100 times full query, consumption of nearly 4 seconds, unacceptable.



Note:



Why not serialize directly? Because my design table structure is variable, using JSON's key-value is easy to expand the table structure.



Gson the goods, unexpectedly one step the JSON string into an object. I can only say, too over-architecture. Too much API design.



Jackson used the Jsonnode, the essence or the key-value pair, the right design, very convenient.



Conclusion:



If you want to use JSON, Json-lib is a piece of crap, it's a lab work ... Use Jackson, please.





2. Cloneable interface?


I have always had a point of view that Java provides native API performance that is more efficient than any of its own.



Unfortunately, cloneable interface first, there is no public object clone. I don't know what kind of plane he's doing. The inheritance interface is not public yet. To call Object.clone yourself. Second, a shallow copy, if there is an object array, or a pointer reference.



Usr_equipment implements Cloneable



{



@Override



Public Object Clone () {Super.clone ();}
}



Unfortunately, I really do not know what this cloneable designed to do.



So I designed a icloneable extends Cloneable interface, the clone exposed.





3. Shallow copy into deep copy?


In order to implement a deep copy, it is necessary to use recursive property traversal of the entire object. The core of the whole magic is beancopier. Performance is more powerful than Beanmap! Let me release the code first:


 
package com.xtar.common.structure;
 
import java.lang.reflect.Array;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;
 
import com.xtar.common.interfaces.ICloneable;
import com.xtar.common.tool.ParserHelper;
 
public class CloneableBase implements ICloneable
{
    private static ConcurrentMap<Class<?>, BeanCopier> beanCopiers = new ConcurrentHashMap<Class<?>, BeanCopier>();
 
    @Override
    public Object clone()
    {
        try
        {
            Object clone = this.getClass().newInstance();
 
            BeanCopier copier = _createCopier(this.getClass());
 
            copier.copy(this, clone, new Converter()
            {
                @Override
                public Object convert(Object pojo, Class fieldType, Object fieldName)
                {
                    return _clone(pojo);
                }
            });
 
            return clone;
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
 
    private static Object _clone(Object bean)
    {
        if (bean == null)
        {
            return null;
        }
        else if (bean instanceof ICloneable)
        {
            return ((ICloneable) bean).clone();
        }
        else
        {
 
                    if (bean.getClass().isArray() && !bean.getClass().getComponentType().equals(byte.class))
                    {
                        int length = Array.getLength(bean);
                        Object clone = Array.newInstance(bean.getClass().getComponentType(), length);
                        for (int i = 0; i < length; i++)
                        {
                            Array.set(clone, i, _clone(Array.get(bean, i)));
                        }
                        return clone;
                    }
                    else
                    {
                        return bean;
                    }
            }
        }
    }
 
    private static BeanCopier _createCopier(Class<?> clz)
    {
        if (beanCopiers.containsKey(clz))
            return beanCopiers.get(clz);
        beanCopiers.putIfAbsent(clz, BeanCopier.create(clz, clz, true));
        return beanCopiers.get(clz);
 
    }
}


Above is the magic core of the entire deep copy.



1) using Beancopier, and caching this object, performance increased by 50%, from 1s down to 600ms.



2) determine the array, if it is a byte[] type, directly using a shallow copy. This is a special object.



Test it down twice times faster than with Beanmap. The same object, Beanmap need 1700ms, and beancopier only need 500ms.





4. Conclusion


I think this is the best way to do it. (binary serialization is not tested). Deep copies can be implemented as long as their objects inherit the cloneablebase.



A high-performance fast deep copy method for Java. Cloneable?


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.