Thursday, November 14, 2019

arrays - The assignment operator in Java




class App{   
int[] a;


private void firstFunction(){
int[] b = {1, 2, 3, 4};
a = new int[4];
a = b;
}

private void secondFunction(){
for(int i=0; i }

}


Both a and b are pointers toward the same memory. When b is out of scope, the allocated memory should be released and a should become null, right? Or it is based on reference-counting approach, with b being deleted but memory still exists?


Answer



Neither. Java's garbage collection is based on reachability -- whether an object can be reached by some chain of references from some set of known starting points. More info from Oracle



Thus, when b goes out of scope, as the array is still reachable through a, the array is not deallocated.



Reference counting isn't used in Java, although at least in this case I think it will have the same effect as Java's GC. Jon Skeet touches on the subject in this answer, and says that it isn't used because it detrimentally affects performance and fails for cycles in the object graph. This post by Brad Abrams expands on that.



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...