How can I make an object active in memory only for some part of the function in JAVA?

I have a function that works for a long time, and I declare and assign an object inside this function. Now, from what I think I know, this object will live in memory at least until this function is launched, and after that it will be available for garbage collection if no other object refers to it . Now I want this object to be available for garbage collection before even the function is completed. In the encoder:

     public void foo(){
             String title;
             Object goo=getObject();  //getObject is some other function 
     //which returns Object and can be null and I want Object to be in memory from here
             if(goo!=null)title=goo.getString("title"); 
           //after the last line of code I want Object to be available for garbage 
    // collection because below is a long running task which doesn't require Object.

              for(int i=0;i <1000000;i++)     //long running task
        {
        //some mischief inside with title 
        }

            }

, for. - , . , ?

+4
4

, . Java , , .

, . JVM . , , goo , Java . , goo , JVM , .

. Q & A.

+4

, , null goo goo. , , .

, goo , , JIT/GC ablity, . .

+3

goo = null;

, , gc , .

. , GC

+2

, if block. ,

{ // <-- add this
    Object goo = getObject();
    if (goo != null) { // <-- just because you can omit braces, doesn't mean 
                       //     you should.
        title = goo.getString("title"); 
    }
} // <-- and this, and then goo is out of scope.
+2

Source: https://habr.com/ru/post/1687969/


All Articles