Can I set object (referring to anonymous inner class) to "null" inside its method?
I have a private
method inside a class A
as below:
class A
{
//...
private void initPlay(final long duration)
{
myTimer = new Utils.Timer(duration) // non-static member variable
{
@Override
public void timerExpired(Object o)
{
// ... do something
myTimer = null;
initReplay(); // unrelated method
}
};
}
}
myTimer
is r开发者_JAVA百科eferring an anounymous inner class
, which implements Utils.Timer
's abstract method timerExpired(Object)
.
Now when timer expired and that method is invoked I am simply setting myTimer = null;
. This assignment is made just to make sure that, there are no references to that object and GC can take it away whenever finds.
Is it ok to do it ? Is there any side effect (apart from null checks, which I have already taken care) ?
If myTimer
is an instance (or static) variable, then you can, yes - but you should be wary of the possibility of initPlay
being called twice - which would result in the first one being eligible for garbage collection early (assuming nothing else holds a reference to the timer).
If you need to access the local variable myTimer you should declare your variable myTimer with final key. But if you do that, the local variable myTimer can be reassigned. In fact, you don't need to do that, GC will collect it auto.
精彩评论