Does Java have automatic garbage collection? [closed]
开发者_Go百科
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this questionDoes it happen automatically? How do can run it?
Yes, garbage colelction happens automatically. You should not need to manually run it, nor is it recommended. The whole point of garbage collection is that it should be transparent.
Please see: Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine
[BTW, there are many questions on SO related to java garbage collection]
Yes it does. You can run System.gc()
but it is not recommended. Also you still can have memory leaks
The garbage collector will automatically collect when it needs to. No need to do anything yourself unless you really have to.
With the Java Virtual Machine, data (objects, arrays of primitives) is stored in the heap which is a shared region of memory that all JVM thread can access. Memory is allocated for the heap when the JVM starts (and may expand to a certain limit at runtime depending on the configuration). Whenever a new object is created, a portion of the heap is allocated to store it.
When the heap is full i.e. when no further allocations can be done (this is an over simplified version, I'm skipping details), the garbage collector is started automatically to reclaim memory space. Basically, any object which is not referenced by an active thread may be safely de-allocated.
Note that the garbage collector thread normally runs as a very low process thread but, once kicked in, it can not be suspended until the task completes.
Java does have automatic garbage collection. However there are some things you need to do. Java only GCs those objects in the heap that have no reference. What you do is assign null value the variable you no longer require and want the memory in heap to be freed. If you do not assign null to the variables, the objects in the heap will have a reference and will occupy the memory space even if you do not need them anymore.
精彩评论