I wrote this code:
ScheduledExecutorService ExtractorTimer=Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> SchedulerHandle;
SchedulerHandle =ExtractorTimer.scheduleWithFixedDelay(
new Runnable() {
public void run() {
if(DB.buildConnection()){
SchedulerHandle.cancel(false);
}
}
},0, 60,java.util.concurrent.TimeUnit.SECONDS);
It gives this:
Variable SchedulerHandle might not have benn initialized
What is the problem?
How can I fix it?
Because SchedulerHandle is final and you didn’t define it right away, your compiler warns you, that it might not been initialized in the run() method.Simply do:
Update: That was simply wrong. Let’s see, you want to call DB.buildConnection() every 60 seconds until it returns true. Unfortunately you can’t reference SchedulerHandle returned from scheduleWithFixedDelay() in the Runnable you call the method with, because the Runnable has to be defined first – but it doesn’t know what SchedulerHandle is, because it doesn’t exist at that point.
So an alternative way of canceling the process is to terminate your ScheduledExecutorService, like so:
But note, that if you do this, you can’t reuse ExtractorTimer and any given task will be canceled! Future schedule()s will also not execute. The only way to make it useable again is to create a new ScheduledExecutorService – that’s the drawback of this approach.
So if you are okay using ExtractorTimer only for this one task, everything should be fine.