Home > Back-end >  Where are variables allocated when referenced within posted Runnables?
Where are variables allocated when referenced within posted Runnables?

Time:02-15

My understanding (though it could be incorrect!) is that in Method1(), myInt will be allocated on the stack and then deallocated upon returning from the method.

My question is about where myInt will be allocated in Method2() because the method could be returned from (and thus myInt deallocated from the stack) before the Runnable posted to the UI thread's Looper is executed? And yet, in testing, the Runnable does still seem to be able to reference myInt. Does the compiler automatically move variables referenced within posted Runnables to the heap, even if they would ordinarily be allocated on the stack?

public void Method1()
{
    int myInt = 0;

    /* Do some operations on myInt */
    myInt = 5;
}

public void Method2()
{
    int myInt = 0;

    RunOnUiThread(() =>
    {
        /* Do some operations on myInt within a Runnable posted to the UI thread's Looper */
        myInt = 5;
    });
}

CodePudding user response:

Method2 creates a Closure. As an implementation detail (ie: the language designers are free to change this), the compiler makes a closure work by creating a class behind the scenes where the captured value is now a member property, and access to the value is now rewritten as access to the property in an instance of the class.

In other words, there is now a class instance allocated on the heap holding this value.

Again, this is an implementation detail. It's possible (though unlikely) a future revision might do something like allocate an additional stack frame instead of the class instance.

  • Related