Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an Object live in memory only for some part of a function in JAVA?

I have a function which runs for a long time and I declare and assign an object inside that function. Now from what I think I know this object will live in memory atleast for as long as this function is running and after that it will be available for garbage collection if no other object references it. Now, I want this object to be available for garbage collection before even function is completed running. In the coding mannger:

     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 
        }

            }

Now from the above task what I want Object to be available for garbage collection before the for loop starts. Can I do something like enclose two lines of code before for loop to be inside curly braces, If no what can I do to achieve this task ?

like image 459
Kartik Watwani Avatar asked Dec 18 '22 03:12

Kartik Watwani


2 Answers

The object will not stay around during the loop even if you do not do anything. Java will figure out that the object is not reachable once your code passes the point of last access.

A reachable object is any object that can be accessed in any potential continuing computation from any live thread. JVMs are pretty smart these days at figuring out reachability. If it sees that there is no code continuation that could possibly access goo during or after the loop, Java makes the object eligible for garbage collection after the point of last access. Even if the last access checker is very conservative, having no accesses to goo is sufficient to convince JVM that the object is no longer reachable.

See this Q&A for more details.

like image 176
Sergey Kalinichenko Avatar answered Dec 29 '22 01:12

Sergey Kalinichenko


After you have finished with the object, assigning null to goo will make it no longer reachable via goo. If there is nothing else keeping it reachable, it will then be eligible for garbage collection.

Arranging your code so that the goo variable goes out of scope might have the same effect, but that approach depends on the JIT compiler / GC's ablity to optimize away the tracing of out-of-scope variables. That is platform dependent.

like image 22
Stephen C Avatar answered Dec 29 '22 00:12

Stephen C