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;
});
}