Delete unused variable's memory in java

前端 未结 8 450
不知归路
不知归路 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 12:50

    You can assign null to variables, verify that there is no any references to these objects and call System.gc(), but is is only a suggestion for JVM to call a GC, but there is no guarantee. Garbage collection cal slows your application up to a freeze (stop-the-world GC).

    0 讨论(0)
  • 2020-12-28 12:52

    You can call System.gc(); which might lead the garbage collector to cleanup. But sure this will affect the performance of your application. In general it doesn't make sense to try to "optimize" anything here.

    0 讨论(0)
  • 2020-12-28 12:57

    A very common suggestion is to use System.gc() Which the JVM may choose to ignore. You can also use the scoping, for example:

    import java.io.*;
    public class AutoVariableTest
    {
        public static void main(String[] args) throws Exception
        {
            String fileName = "test.txt";
            {// This is local block just to keep auto variable in check
                File file = new File(fileName); // file is not visible outside the scope and is available for garbage collection
                BufferedReader br = null;
    
                try{
                    br = new BufferedReader(new FileReader(file));
                    // ...
                }finally{
                    if(br != null)
                        br.close();
                }
            }// local block end
        }
    }
    
    0 讨论(0)
  • 2020-12-28 12:59

    There is no direct and immediate way to free memory in java. You might try to persuade the garbage collector to take away some object using the well known:

    Object obj = new Object();
    // use obj
    obj = null;
    System.gc();
    

    but there is no guarantee that this will actually free memory immediately.

    While this applies to heap memory, stack allocated items can only be freed when the function returns.

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

    Java is not suitable if you are trying to manage memory ! Or you write your own Garbage Collection mechanism in JVM if you have lots of time

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

    If you intend to reduce the amount of memory used after a certain point, you might be better off using arrays for your variables so that you can set an array to null once it is no longer necessary. This way, it takes much less time for the garbage collector to clean up all of your data.

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