6

[Check the bottom of the question for updates]

As in the title, I'd like to write a class which takes in a method and executes it in a new Thread. I lurked around SO and came up with something like:

import java.util.concurrent.Callable;

public class MyExecutor<T> implements Runnable{

    private Callable<T> method;


    public <T> MyExecutor(Callable<T> pMethod){
        this.method = pMethod;
    }

    @Override
    public void run() {
        try {
            // start a new Thread, then
            method.call();
        } catch (Exception e) {
            System.err.println("Failed calling method "+method.getClass());
            e.printStackTrace();
        }

    }

}

However Eclipse warns me that, inside the constructor, in

this.method = pMethod;

I cannot convert from Callable <T> to Callable <T>.

It smells like I'm doing something entirely wrong, but I can't grasp it.

UPDATE

Turns out I was reinventing the wheel, what I wanted to do can be attained like this:

public class MyExecutor implements Executor{


    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }

}

In the main flow a method can be executed in a new thread like this:

    MyExecutor myExec = new MyExecutor();

    myExec.execute(new Runnable() {

        @Override
        public void run() {
            myMethod();
        }
    });
Tom
  • 92
  • 13

1 Answers1

6

Since you added a type parameter <T> to your constructor, it shadows the type parameter for the class. Therefore, the T for the constructor argument pMethod is a different T than the class parameter, which is what Eclipse is warning you about. Just change the signature for the constructor to public MyExecutor(...).

Piotr Wilkin
  • 3,446
  • 10
  • 18
  • Thank you, you're right. Since we're here, does the idea itself (passing a method to the class, creating a thread inside my generic class and executing my method) make sense? Is it decent practice? Marked as the solution anyway. – Tom Aug 09 '16 at 11:00
  • 5
    @Tom You're reinventing the wheel basically. The JDK already has executors, that provide you with the functionality (and more, with `Future` and other such things). At least you know that your idea is valid enough to include in the runtime ;) – Kayaman Aug 09 '16 at 11:08
  • As Kayaman says - not only is it valid practice, it's already done. You might want to look into the `java.util.concurrent.Executor` hierarchy. – Piotr Wilkin Aug 09 '16 at 11:26
  • Thank you all, every day is a school day :) – Tom Aug 09 '16 at 12:49
  • 1
    @Tom, you aren't passing a method. You are passing an _object_ that implements the `Callable` interface. Java does not have functional types. Java8 fakes them with `@Functional` interfaces. – Solomon Slow Aug 09 '16 at 13:27