A careless errors - the object copy yet?

Foreword

This project have been busy for a while, now he can finally get down to sum up this period of development experience, going to a New Year's papers say I made a mistake under, or negligence can be said, I hope to give you some help ~

Recently, I also have some things not liking things in life all likelihood, tried, survived the boil night, I do not regret enough. I hope everyone in the New Year along smoothly Lee ~

Problem Description

  • Scene: Business sinking , the RPC caller's business logic to sink to the RPC service side, provide a common interface.

Code comparison

// 调用RPC服务获取Mission对象
ResponseDTO<Mission> res = missionService.getMissionById(missionId);
// 下沉后直接通过缓存获取对象(RPC服务原有的方法)
Mission mission = missionCache.getMissionById(missionId);
复制代码

Code issues

// set mission对象属性 (其实set很不合理,应该是一个BO)
mission.setA(A);
mission.setB(B);
// 根据mission对象属性触发业务逻辑
// ...
复制代码

According to the above changes, I will find just the logical RPC call to the service side of the sinking, calling the method of obtaining the service side of the missionobject, but there is a problem, obviously, leads to a direct result of display disorder .

problem analysis

Presumably, we all know the reason, as follows:

1, the object acquired through the RPC deserialized, not removed from the object database, the object attribute does not affect the value of SET cache. 2, taken out of the cache is retrieved object database (cache key is missionId) is taken from the database objects, object properties SET will affect other users' access.

Deserialize resulting object is why the new object?

  • The process of converting an object into a binary stream is called serialization , binary transfer process into objects called deserialization .
  • The following sample code to an example, look serialized, after the object deserialization is consistent with the original object.
package serialization;// Java code for serialization and deserialization
// of a Java object 
import java.io.*;

class Demo implements java.io.Serializable
{
    public int a;
    public String b;

    // Default constructor 
    public Demo(int a, String b)
    {
        this.a = a;
        this.b = b;
    }

}

public class TestObject
{
    public static void main(String[] args)
    {
        Demo object = new Demo(1, "geeksforgeeks");
        String filename = "file.ser";

        // Serialization  
        try
        {
            //Saving of object in a file 
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);

            // Method for serialization of object 
            out.writeObject(object);

            out.close();
            file.close();

            System.out.println("Object has been serialized");
            System.out.println(object.toString());

        }

        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }


        Demo object1 = null;

        // Deserialization 
        try
        {
            // Reading the object from a file 
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);

            // Method for deserialization of object 
            object1 = (Demo)in.readObject();

            in.close();
            file.close();

            System.out.println("Object has been deserialized ");
            System.out.println(object1.toString());
        }

        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }

        catch(ClassNotFoundException ex)
        {
            System.out.println("ClassNotFoundException is caught");
        }

    }
} 
复制代码

operation result

  • We can see, after deserialization, the generated objects are not the same
Object has been serialized
serialization.Demo@23fc625e
Object has been deserialized 
serialization.Demo@1f17ae12
复制代码
  • For the above-described problems encountered, it is necessary to use an object copying process, generating a new object corresponding service logic processing.

Object copy

  • Copy of the object is divided into deep copy , shallow copy , following differences:

In the Java language, into the data type value type (basic data types) and reference types, including value type int, double, byte, boolean, char and other simple data types, including complex type reference type class, an interface, an array like. The main difference between deep and shallow clone clone that supports copy member variables of a reference type, the following will both be described in detail.

The most brutal get/setmethods

Implement clonableInterface

class Demo implements Cloneable {
    public int a;
    public String b;

    // Default constructor 
    public Demo(int a, String b) {
        this.a = a;
        this.b = b;
    }

    @Override
    protected Object clone() {
        Demo demo = null;
        try {
            demo = (Demo) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return demo;
    }

    public static void main(String[] args) {
        Demo demo1 = new Demo(1, "1");
        Demo demo2 = (Demo) demo1.clone();
        System.out.println(demo1 == demo2);
    }
}
复制代码

Use apacheor springutility classes,BeanUtils

1、spring (org.springframework.beans.BeanUtils) 2、apache commons-beanutils(org.apache.commons.beanutils.BeanUtils)

// org.springframework.beans.BeanUtils,
// a拷贝到b
// org.apache.commons.beanutils.BeanUtils,
// b拷贝到a
BeanUtils.copyProperties(a, b);
复制代码
  • This small mistake, I recently made a 2, for all of us must not make mistakes, especially when the RPC business logic sinking, need to pay attention to these, because the RPC caller got after deserialization target set number of operating properties (property set unreasonable) , if without thinking, you will have some problems.

Epilogue

  • RPC after deserialization acquired a new object.
  • When required attribute set object, to analyze the context, the results would not affect the other requests.

Finally, I hope that after some failures after a possible fall from where from where to get up.

Guess you like

Origin juejin.im/post/5e14434bf265da5d220209af