Object Access Analysis

Object reference and object assignment


1. Object Reference and Object Creation

Object obj = new Object(); 


  • Object: class object, stored in the method area
  • Object obj: class reference variable, that is, the reference to the instance object of the class, the local variable table stored in the Java virtual machine stack
  • new Object: forms a structured memory that stores all instance data values ​​of the Object type (value data of each instance field in the object), and stores it in the heap area
  • (): The constructor in the class object, initializes the generated object; there must be a constructor in the class object, and the system provides a parameterless constructor by default. If other constructors are actually declared, the system does not provide a default constructor
  • =: The operator makes the object reference point to the Object object just created, that is, the first address of the space in the heap where new Object() is stored in obj


Object obj = null ; // ojb object reference points to null
obj = new Object(); // obj object reference points to new object
Object obj1 = obj ; // Now obj obj1 points to an object

The relationship between object references and objects
  • An object reference can point to 0 or 1 objects (that is, an object reference can point to null)
  • An object can have N references pointing to it (that is, the first address of the space in the heap of the same object stored by the object reference)
  • Operate on an object by referencing an object


// obj originally points to new Object(); if obj1 = null at this time;
// Then when obj points to the new object, the original unreferenced new Object()
// Will become the processing object of the garbage collection mechanism, when the collection is controlled by the GC
obj = new ObjectOther(); // Assign value to obj again, pointing to other objects
System.out.print("abc") ; // anonymous string object
System.out.print(new A().getA()); // use the methods in the anonymous object directly

  • Temporary objects: The relationship of an object to a reference will last until the object is reclaimed. e.g. anonymous object



2. There are two ways to reference objects of reference

type

Address information

2.

The object address is stored directly in the reference. The object address stores the address information pointing to the type data in the method area.

3.
The biggest advantage of the handle is that when the object is moved, only the instance data pointer of the handle needs to be changed. ; and the reference does not need to be modified. The
direct pointer access method is fast and saves the time of a pointer positioning. Because object access is very frequent in Java, it is very beneficial. The virtual machine Sun Hot Spot adopts this method

.

Pass by value, not pass by reference;
for basic data types, the value of the data itself is passed; for
reference data types, the reference of the object is passed, that is, the address value stored in the heap;

package com.java.study.test.unit8;

public class ParameterMethodMain {

	private Integer i ;
	
	private Integer j ;

	private ParameterMethodMain(){
		super();
	}
	
	private ParameterMethodMain(Integer i ,Integer j){
		this.i = i ;
		this.j = j ;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// 1. Basic data type, the value itself is passed in the method
		// The modification of the value in the method does not affect the size of the original value;
		// Reassignment: that is, changing the content of the original variable will change the size of the original value
		// int corresponds to the wrapper class Integer, Integer is final modified, same as String, cannot be changed
		int a = 0 ;
		changeMethodBasic(a);
		System.out.println(a); // 0
		a = changeMethodBasic(a);
		System.out.println(a); // 100
		
		// 2. Reference data type
		ParameterMethodMain main = new ParameterMethodMain();
		main.setI(1);
		main.setJ(2);
		// A reference to the object data type is passed, pointing to an object in the same heap,
		// The main object reference in the Main() method and the main reference in the method point to the same object
		// so object changes are shared
		changeMethodRefence(main);
		System.out.println("i="+main.getI()+" j="+main.getJ());// i=3 j=4
		// parameters in changeMethodRefenceNew ParameterMethodMain main
		// Just received the address of the object passed by the main object reference in Main(), and has nothing to do with the main object
		// Reassign the formal parameter main in changeMethodRefenceNew, regardless of the main object in the Main() method
		// just named the same here
		changeMethodRefenceNew(main);
		System.out.println("i="+main.getI()+" j="+main.getJ());// i=3 j=4
		// Changed the content pointed to by the current object, pointing to the new object
		// Forced to change the address stored in the reference of the main object in the Main() method
		main = changeMethodRefenceNew(main);
		System.out.println("i="+main.getI()+" j="+main.getJ());// i=5 j=6

		// 3. String is a reference data type, but it is special because String is characterized by immutable objects;
		// Any operation on a reference to an existing string object will result in a new object
		String str = new String("abc") ;
		// The formal parameter String str in the changeStr method receives the transfer of the object reference address of str in the Main() method
		// The reassignment of str in changeStr actually creates a new object bcd and points str to the bcd object
		// But changeStr is only valid inside the method
		changeStr(str);
		System.out.println(str);
		// Equivalent to the str reassignment of Main(), pointing to the address of the new object
		str = changeStr(str);
		System.out.println(str);
		
	}

	public static int changeMethodBasic(int a){
		System.out.println("a="+a); // a=0
		a = 100 ;
		System.out.println("a="+a); // a=100
		return a ;
	}
	
	public static void changeMethodRefence(ParameterMethodMain main){
		main.setI(3);
		main.setJ(4);
	}
	
	public static ParameterMethodMain changeMethodRefenceNew(ParameterMethodMain main){
		ParameterMethodMain newMain = new ParameterMethodMain();
		newMain.setI(5);
		newMain.setJ(6);
		main = newMain;
		return main;
	}
	
	public static String changeStr(String a){
		a = "bcd";
		return a ;
	}
	
	
	
	public Integer getI() {
		return i;
	}

	public void setI(Integer i) {
		this.i = i;
	}

	public Integer getJ() {
		return j;
	}

	public void setJ(Integer j) {
		this.j = j;
	}
}


  • Pass parameters in methods, pass by value instead of by reference
  • For reference data types, the formal parameter in the method is a copy of the reference address passed in from the calling location, which is equivalent to an additional object reference pointing to the object at the same time. Therefore, when the formal parameter in the method modifies the object, it will affect the calling of this method. However, swapping places and repointing to the new object will not affect the object in the calling method, that is, the object reference in the method is equivalent to breaking the binding relationship with this object, but with the object reference in the calling method. irrelevant
  • For String, it is a reference data type, but the characteristic of String itself is that the object is immutable. The formal parameter in the method receives the passed reference address, and any modification to the object will generate a new String object, that is, the object reference in the formal parameter points to new object
  • For primitive data types, the value passed


4. Reference

Index strength: strong reference > soft reference > weak reference > virtual reference, related to GC

Compared strong citation soft reference weak reference phantom reference
English Strong Reference SoftReference WeakHashMap PhantomRefrence
GC Live in the JVM for as long as possible, and will be recycled after GC execution when there are no objects pointing to it The biggest difference is that SoftReference will keep references as long as possible until the JVM runs out of memory and will not be reclaimed (virtual machine guarantee), this feature makes SoftReference very suitable for caching applications When the referenced object no longer has a strong reference in the JVM, the weak reference will be automatically reclaimed after GC; in the process of scanning the memory area under its jurisdiction by the garbage collector thread, once an object with only weak reference is found, Whether the current memory space is sufficient or not, its memory will be reclaimed After establishing a virtual reference, the result returned by the get method is always null. Through the source code, you will find that the virtual reference will write the referenced object into the referent, but the return result of the get method is null; it may be destroyed by the garbage collector at any time. Recycle
effect - Building a cache of sensitive data using soft references - Virtual references are mainly used to track the activities of objects being reclaimed by the garbage collector; when the garbage collector is ready to reclaim an object, if it finds that it still has a virtual reference, it will add the virtual reference to the object before reclaiming the memory of the object. In the associated reference queue, the program can know whether the referenced object will be garbage collected by judging whether a virtual reference has been added to the reference queue. If the program finds that a virtual reference has been added to the reference queue, it can take necessary action before the memory of the referenced object is reclaimed
ReferenceQueue - - optional must be used together
definition Refers to the ubiquitous references in the program code, such as Object obj = new Object(), as long as the strong reference still exists, the garbage collector will never reclaim the referenced object It is used to describe some objects that are still useful but not necessary. For objects associated with soft references, these objects will be listed in the reclamation range for a second reclamation before a memory overflow exception occurs in the system. If there is not enough memory for this collection, an out-of-memory exception will be thrown Used to describe non-essential objects, but its strength is weaker than soft references. Objects associated with weak references can only survive until the next garbage collection is sent. When the garbage collector works, objects that are only associated with weak references are reclaimed regardless of whether the current memory is sufficient. Once a weak reference object is reclaimed by the garbage collector, it is added to a registered reference queue. Phantom references, also known as ghost references or phantom references, are the weakest kind of reference relationship. An object that holds a phantom reference is almost the same as having no reference, and may be reclaimed by the garbage collector at any time. When trying to get a strong reference through the get() method of a virtual reference, it always fails. Also, virtual references must be used with reference queues, which are used to track the garbage collection process


V. Judgment of Object Accessibility

  • Object reference relationship: According to who the object is referenced by, it is referenced by one or more objects, forming a tree structure with the root level as the vertex; instead of counting which object is referenced by the current object
  • Single reference path reachability judgment: In this path, the weakest reference determines the reachability of the object.
  • Reachability judgment of multiple reference paths: Among several paths, the reference of the strongest one determines the reachability of the object.


Example:
The direction of the arrow represents the direction of the reference, and the object pointed to is the referenced object
A-->B-->C-->D
A-->E-->F-->D
B-->C Strong reference, C-->D weak reference, B-->C-->D weak reference
E-->F strong reference, F-->D soft reference, E-->F-->D soft reference
D Objects are soft references

Blog reference:
Java reference types
in-depth understanding of StrongReference, SoftReference, WeakReference and PhantomReference
object access analysis
on java object reference and object assignment

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326560531&siteId=291194637