Recommend a better way to turn synchronous methods to asynchronous in Java

你。 提交于 2019-12-01 09:09:47

This is the recommended way of doing it:

abstract public class Action<T> implements Runnable {
  private final T param;

  public Action(T param) {
    this.param = param;
  }

  @Override
  public final void run() {
    work(param);
  }

  abstract protected void work(T param);
}

with:

ExecutorService exec = Executors.newSingleThreadExecutor();
while (/* more actions need to be done */) {
  exec.submit(action);
}
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

The normal way to handle this is to use the java 5 executors framework, like shown here. This'll allow you to use the same pattern for both synchronous and asynchronous implementations, and you can just choose which ExecutorService to use.

But that is the same thing as krosenvoid, it means that a wrapper class is needed for every method, implementing a work(param) method now.

Either you go for something that is fully dynamic and reflective, where you pass String for method name and Object for parameter. Because Java is statically typed (unlike dynamic language like Groovy) that will be horrible and probably full of casting, but you can do it.

You current solution lists the asynchronous method with enums. So it's not fully dynamic and extensible neither without changing the code. That is, you will need to add a new enum for each new method.

public static enum ActionEnum{
          NEW, CHECK, UPDATE, DELETE, DISPLAY;
}

If it's ok for you, it should also be ok to use Action or Callable, as suggested in the other answers. For each new method you will need to write a new Action or Callable so that the method invocation is statically defined.

 protected void work(String param)
 {
      myObject.theMethodToDispatch( param );
 }

I agree that it's a bit more boilerplate code, but that's still fairly small. The big win is that then your code is not reflective (and there should be no casting) and you have the benefit of statically typed languages: you can refactor method names, the compiler warns you if type parameter mismatch, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!