Search code examples
javascheduledexecutorservicequantifiers

Method called in run method of a timer returns a value I need to use upstream


I have the following timer code, and based on the execution of the run method, whether it was successful or not, I would like to return a boolean.

However I get the error message: Local variable connected defined in an enclosing scope must be final or effectively final.

How do I work around this to accomplish what I want? Here is the code:

    private boolean getSwitchesOnRc(NamedPipeClient pipe, DV_RC_EntryPoint rc_EntryPoint, int allowedAttempts, int counter){
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    boolean connected = false;
    ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            connected = attemptRetrievalOfSwitches(pipe, rc_EntryPoint, allowedAttempts, counter);
        }}, 1, TimeUnit.MINUTES);


    return connected; 
}

Solution

  • You need to schedule a Callable rather than a Runnable to do this.

    This would do what you want:

    ScheduledFuture<Boolean> countdown = scheduler.schedule(new Callable<Boolean>() {
        public Boolean call() {
            return attemptRetrieval(...);
        }}, 1, TimeUnit.MINUTES);
    
    return countdown.get();
    

    Note that this method will block until the scheduled call has completed.