I have a class which implements the callable interface. I want to schedule a task for the class using scheduleAtFixedRate method of ScheduledExecutorService interface. However scheduleAtFixedRate needs a runnable object as a command which it can schedule.
Hence I need some way in which I can convert a callable to a runnable. I tried simple casting but that is not working.
SAMPLE CODE:
package org.study.threading.executorDemo;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class ScheduledExecutionTest implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("inside the call method");
return null;
}
}
public class ScheduledExecution {
public static void main(String[] args) {
ScheduledExecutorService sec = Executors.newScheduledThreadPool(10);
sec.scheduleAtFixedRate(new ScheduledExecutionTest(), 5, 2, TimeUnit.SECONDS);
}
}
FutureTask task1 = new FutureTask(Callable<V> callable)
Now this task1 is runnable because:
class FutureTask<V> implements RunnableFuture<V>
RunnableFuture<V> extends Runnable, Future<V>
So from above two relations, task1 is runnable and can be used inside Executor.execute(Runnable)
method
Assuming you don't really need the Callable
to return anything useful, you can wrap a Callable as a Runnable
Runnable run = new Runnable() {
public void run() {
try {
Object o = callable.call();
System.out.println("Returned " + o);
} catch (Exception e) {
e.printStackTrace();
}
}
};
or in Java 8
Runnable run = () -> {
try {
Object o = callable.call();
System.out.println("Returned " + o);
} catch (Exception e) {
e.printStackTrace();
}
};
This is quite messy but it sounds like the Callable should have been a Runnable in the first place and you wouldn't have to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With