开发者

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

开发者 https://www.devze.com 2022-12-23 01:33 出处:网络
In a classes are some methods that are run synchronously. I would like them to run asynchronously, the first idea was to wrap it, and use switch enum to decide which function should be called. But for

In a classes are some methods that are run synchronously. I would like them to run asynchronously, the first idea was to wrap it, and use switch enum to decide which function should be called. But for every method called, I needed a new method in the wrapper class and a new enum. It looks like this:

public class QueuedShow implements InterfaceShowAlert, Runnable {
    private Class Action {
       String param1;
       public static enum ActionEnum{
          NEW, CHECK, UPDATE, DELETE, DISPLAY;
       }
       public ActionEnum todo;
       public Action(ActionEnum todo, Object param){
          this.todo=todo;
          this.param1=param;
       }
    }
    private BlockingQueue<Action> actionList;
    public void run(){
       while(true){
           Action action=actionList.take(); //THIS waits until queue isn't empty
           switch(action.todo){
           case NEW: //Call original function
              ....
           }
       }
    }
    public void new(String param){
       actionList.add(new Action(NEW, param));
    }
}

Then I learned about reflection and I got a new idea. That is to invoke methods using strings instead of direct method calls. The wrapper class reads and parses the strings, and gets the class and containing method using reflection. It puts the parameters and Method object into a class, which is put into a queue. Now the class uses Method.invoke(p开发者_运维问答arams) instead of using a enum to switch. But the problem of this is that compiler time type checking is lost.

Of course, all this works for only methods that are void, but of course we could use the Future class to return values too.

Now is there any framework that already has implemented turning synchronous calls to asynchronous ones, or do you know of any other method that does this.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消