Harriet
Harriet

Reputation: 1713

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

Upvotes: 0

Views: 1325

Answers (2)

mikea
mikea

Reputation: 6667

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.

Upvotes: 0

adekcz
adekcz

Reputation: 410

Just use callable insted of Runnable:

<V> ScheduledFuture<V>  schedule​(Callable<V> callable, long delay, TimeUnit unit)  
Creates and executes a ScheduledFuture that becomes enabled after the given delay.

main difference is, that Callable can return value (directly by calling return statement).

then instead of

return connected; 

will be

return countdown.get();

Upvotes: 1

Related Questions