Delete unused variable's memory in java

前端 未结 8 626
不知归路
不知归路 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条回答
  •  梦毁少年i
    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
        }
    }
    

提交回复
热议问题