Reputation: 684
I want to return boolean value from the below method but it gives me error message saying
"Local variable stopped is access from within inner class;
needs to be declared final."
But if I declare stopped as final I can't change it's value.
I know it is due to Timer. Please suggest !
public boolean requestTimer(final Club club,final String msisdn, final int time) {
boolean stopped=false;
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
stopped=checkStopped(club,msisdn); //this line has the error
}
}, time);
return stopped;
}
Upvotes: 0
Views: 1962
Reputation: 5279
You might (ab)use an BooleanHolder:
import org.omg.CORBA.BooleanHolder;
...
final BooleanHolder stopped= new BooleanHolder();
...
stopped.value = checkStopped(club,msisdn);
...
return stopped.value;
Thus, you have a something that is final
, but holds a mutable value. Similar for int etc.
Upvotes: 1
Reputation: 21778
You cannot modify the local variable form the inner class. You could access it, but must be declared final so you cannot change it once assigned.
You could modify the field of the outer class from the inner class no problem. Move the declaration to the field level:
boolean stopped=false;
public boolean requestTimer(final Club club,final String msisdn, final int time)
(...)
and this will work.
If you have a task that must run after scheduled delay and return the result, I would suggest to use Callable instead of the TimeTask
and ScheduledExecutorService
instead of Timer
. Then you will get ScheduledFuture
that will return the needed value, or would suspend the current thread if such is not yet available.
Upvotes: 1
Reputation: 285405
I know it is due to Timer
It has nothing to do with Timer and all to do with your trying to use a local variable in an inner class. Java makes a copy of the local variable that is used in the inner class, and the two variables -- the original and its copy -- risk changing if the original is not declared final.
But if I declare stopped as final I can't change it's value.
True. So you can't do this. A possible solution is for you to not use a local variable. Instead use a field declared in the class.
Upvotes: 1