Java parameter passing mechanism, java parameter passing
The parameter transfer mechanism of java is very similar to that of C and C ++. When I changed a website asynchronous interface two days ago, the code was written by outsourcing, springMVC has a multi-thread mechanism, but a model object is passed when parameters are passed, so all threads share this object, and the result is a mess.
Next let's go to the topic. Let's take a look at the demo code.
public class Model {private int value;public int getValue() {return value;}public void setValue(int value) {this.value = value;}}public class Demo {public static void main(String[] args) {String str = "str";int i = 1;Model model = new Model();model.setValue(1);Demo test = new Demo();test.fun(str, i, model);System.out.println(str+"\t"+i+"\t"+model.getValue());}public void fun(String str,int i,Model model){str="fun_str";i = 2;model.setValue(2);System.out.println(str+"\t"+i+"\t"+model.getValue());}}
In java, all basic types such as String, int, float are passed values, so the result is as follows:
fun_str 2 2str 1 2
The values of the String and int types copy an input function, but the results of the model object are the same. It can be seen that the object is passed by reference. Think about it. If 20 threads share this object, the value will surely be in a mess.
It is useless even if a new object is added to the function (the code below), because such a direct value assignment is also a reference, and the model address is assigned to model2, which is a shortest copy (pointer reference ).
public void fun(String str,int i,Model model){ Model model2 = new Model(); model2 = model; str="fun_str"; i = 2; model2.setValue(2); System.out.println(str+"\t"+i+"\t"+model2.getValue());}
To implement deep copy (a new object with the same name in memory), there are many methods. You can take out all the values of the object and pass the parameter. If there are too many parameters, you can put them in a map, or java should have some object clone functions (the clone of java will be studied in the next issue). If not, write a function and manually copy it to the new object, assign all the original objects to the new objects.