Will the variables in the loop be recycled after each loop?
for example
for (int i=0;i<1000000;i++){
Date date=new Date();
}
This date is not referenced, will it be garbage collected? What happens if the created object is referenced?
Java’s GC includes YGC and FGC.
The date object that is not referenced here will definitely be recycled, but not after each cycle.
The timing of GC is not necessarily related to the execution of your code.
For related knowledge, you can Baidu download java GC
The answer to this question lies in the circumstances under which the jvm's garbage collection mechanism will perform garbage collection.
The role of local variables is {}, that is to say, date is not referenced. When garbage collection is performed, the date here will be recycled.
New an object is stored in the heap, and the newly created object is stored in the eden area. Only when the eden area is full will the Monitor GC be triggered for recycling.
You can add
-XX:+PrintGCDetails
to the running parameters to observe the GC recycling situation.