javamultithreadingrunnablecallablescheduledexecutorservice

How can we convert a callable into a runnable


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

Solution

  • FutureTask task1 = new FutureTask(Callable<V> callable)
    

    Now this task1 is runnable because:

    1. class FutureTask<V> implements RunnableFuture<V>
    2. RunnableFuture<V> extends Runnable, Future<V>

    So from above two relations, task1 is runnable and can be used inside Executor.execute(Runnable) method