Java Magazine, Mar/Apr 2018
ORACLE COM JAVAMAGAZINE MARCH APRIL 2018 75 inside the jvm if r1 sameArea r2 sameArea System out println Same area sameArea This code creates 100 million pairs of rectangles of random size and counts how many pairs are of equal size During each iteration of the for loop a new pair of Rect objects is allocated You would therefore expect 200 million Rect objects to be allocated in the main method 100 million each of r1 and r2 However if an object is created in one method and used exclusively inside that method that is if it is not passed to another method or used as the return value the runtime can potentially do something smarter You can say that the object does not escape and the analysis that the runtime really the JIT compiler does is called escape analysis If the object does not escape then the JVM could for example do something similar to an automatic stack allocation of the object In this case the object would not be allocated on the heap and it would never need to be managed by the garbage collector As soon as the method containing the stack allocated object returned the memory that the object used would immediately be freed In practice the HotSpot VMs C2 JIT compiler does something more sophisticated than stack allocation Lets have a look Within the HotSpot VM source code you can see how the EA analysis system classifies the usage of each object typedef enum NoEscape 1 An object does not escape method or thread and it is not passed to call It could be replaced with scalar
You must have JavaScript enabled to view digital editions.