Delete unused variable's memory in java

前端 未结 8 451
不知归路
不知归路 2020-12-28 12:19

I know that Java have its own garbage collection, but sometimes I want to delete the garbage manually. Is there any way to do the work like that? And considering that I have

相关标签:
8条回答
  • 2020-12-28 13:14

    It's not worth doing this manually, since the garbage collector will usually do a better job, and doing it yourself isn't likely going to make a noticeable difference in your application.

    If you must, you can set the variable references to null, and call System.gc(), and this will invoke the garbage collector manually.

    0 讨论(0)
  • 2020-12-28 13:15

    Why do you want to delete the garbage "manually"? If it's because you're out of memory, recall that Java is going to run garbage collection before actually throwing OutOfMemoryError. And if you are really out of memory, then there is no garbage for even you to manually remove.

    Declaring a variable does not allocate memory on the heap. Making an object with new does. JVMs can do escape analysis to even GC object references that have not gone out of scope but are not used anymore before the end of the method.

    If you mean you proactively want to free up memory at a certain point where system resources are not critical, then use better JVM tuning like using the parallel GC algorithms.

    "Manually" garbage collecting by setting things to null likely slows things down if only because you pay the cost of nulling references pointlessly, or, invoking GC more times than is needed.

    0 讨论(0)
提交回复
热议问题