0

I have a method execute() that runs a Runnable which is declared at the class level:

private Runnable r;
private Model m;

public Action(Model m) {
    this.m = m;
    r = () -> {
        Operation op = new Operation(m);
        op.executeAsync();
    }
}

public void execute() {
    //Do stuff here
    r.run();
}

What is happening is the non-async tasks in execute() are executed, and then r is run to handle asynchronous work that takes several seconds to complete. However, the method does not return as soon as the Runnable is ran. Instead, it returns only when the async stuff is finished. However, if I also run the async tasks that are inside of op in a thread, then it works as expected, with execute() returning as soon as r is ran, and the rest of the async work being done after the method ends. Why doesn't the code I am showing here work as I expected, without wrapping all the async work in op in its own thread?

fojalar
  • 47
  • 8
  • In your `execute` method, you call directly the blocking method. Instead, you should pass the runnable into an executor pool and let it run on another thread. In your current impl, there is no multi threading. `Thread t = new Thread(r); t.start();` is the most simple way of threading this. – Matt Clark Aug 02 '17 at 19:22
  • You should enclose your runnable into a thread and then start it, don't you? `r.run()` -> `(new Thread(r)).start())` – Bruno Zamengo Aug 02 '17 at 19:23
  • You need to create a `new Thread(r)` and then invoke `start()` on it. See the linked question for more details. – yshavit Aug 02 '17 at 19:23
  • Except, it probably should _not_ create a new thread for every new async task. It probably should use an appropriately-sized _thread pool_ to execute the tasks. – Solomon Slow Aug 02 '17 at 21:45

0 Answers0