Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 797
Pulkit Gupta Avatar asked Apr 21 '16 18:04

Pulkit Gupta


2 Answers

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

like image 65
pinkman Avatar answered Sep 28 '22 00:09

pinkman


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.

like image 28
Peter Lawrey Avatar answered Sep 28 '22 01:09

Peter Lawrey