How to mark an object for garbage collection by the GC (Garbage Collector)?

后端 未结 4 1630
清歌不尽
清歌不尽 2021-02-08 06:26

In Java, is there a way to mark an object for garbage collection by the GC, during its next clean up cycle?

I\'ve heard that setting an object to

4条回答
  •  再見小時候
    2021-02-08 06:47

    The Java Garbage Collector works with a mark and sweep method. This means from object that are known to still be in used all references are followed and the objects that are visited in that way are marked. In that way objects with no references at all are not marked and should be sure to be deleted. So you could ensure that all references to this object are removed, so that in the next turn of the Garbage Collector, the item is deleted.

    Additionally you could use

    Runtime.getRuntime().gc();
    

    to indicate that the Garbage Collector should run. Note: you can't be sure that it really runs.

提交回复
热议问题