在 Java 中处理异步响应的设计模式 [英] Design pattern to handle an asynchronous response in Java

查看:31
本文介绍了在 Java 中处理异步响应的设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了类似问答的答案

I read answers from similar Q&A

如何在JAVA? |异步编程设计模式 |
AsyncTask Android - 设计模式和返回值

我看到了很多解决方案,但没有一个真正让我满意.

I see a lot of solutions , but none really satifies me.

监听方式

一旦捕获到结果,就在 onResult 方法中进行处理.

Once the results are caught, the processing is implemented in onResult method.

public interface GeolocationListener {
public void onResult(Address[] addresses);
public void onError(Exception e);
}

这个解决方案不太让我满意,因为我想在 main 方法中处理结果.我讨厌这个接口,因为当返回响应时,它会在 onResult 中进行处理,从而导致处理链并且无法返回main"方法.

This solution doesn't quite satify me , because I want to handle the results in the main method. I hate this interface because when the response is returned, it is processed in onResult resulting in chains of processing and no way to go back to the "main" method.

servlet 方式

public class SignGuestbookServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        // ...
        resp.sendRedirect("/guestbook.jsp");
    }
}

没有公开的 Java 代码调用 servlet.所有的配置都在web.xml中完成

There is no exposed Java code calling the servlet. All the configuration is done in the web.xml

我想要的方式

等待这样的回应

Response a = getResponse();
// wait until the response is received, do not go further
// process
Response b = getResponse();
// wait until the response is received, do not go further
process(a,b);

是否有一种设计模式来处理异步请求并等待上述响应?除了听众以外的其他方式.请不要使用库或框架.

Is there a design pattern to handle the async request and wait for the response like above ? Other way than the listener. Please no library or framework.

编辑感谢到目前为止的答复.我没有给你全貌所以我暴露了Geolocation类我开始实施.我不知道如何实现该方法.有人可以展示如何"吗?他(或她)还必须实现侦听器来检索结果

EDIT Thanks so far the responses. I didn't give you the full picture so I exposed the Geolocation class I started the implementation . I don't know how to implement the method . Can someone shows "how to" ? He (or she) must also implement the listener to retrieve the results

private Address getFullAddress (String text, AddressListener listener, ... ){

    // new Geolocation(text, listener, options).start() 
    // implements Geolocation.GeolocationListener   
    // how to return the Address from the onResult ?
}

推荐答案

异步代码总是可以同步的.最简单/最粗暴的方法是进行异步调用,然后进入一个使当前线程休眠直到值返回的 while 循环.

Asynchronous code can always be made synchronous. The simplest/crudest way is to make the async call, then enter a while loop that just sleeps the current thread until the value comes back.

将异步回调转换为同步代码的代码——同样是一个粗略的实现:

Code that turns an asynchronous callback into synchronous code--again, a crude implementation:

import java.util.concurrent.*;

public class MakeAsynchronousCodeSynchronous {
    public static void main(String[] args) throws Exception {
        final Listener listener = new Listener();
        Runnable delayedTask = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new IllegalStateException("Shouldn't be interrupted", e);
                }
                listener.onResult(123);

            }
        };
        System.out.println(System.currentTimeMillis() + ": Starting task");
        Executors.newSingleThreadExecutor().submit(delayedTask);
        System.out.println(System.currentTimeMillis() + ": Waiting for task to finish");
        while (!listener.isDone()) {
            Thread.sleep(100);
        }
        System.out.println(System.currentTimeMillis() + ": Task finished; result=" + listener.getResult());
    }

    private static class Listener {
        private Integer result;
        private boolean done;

        public void onResult(Integer result) {
            this.result = result;
            this.done = true;
        }

        public boolean isDone() {
            return done;
        }

        public Integer getResult() {
            return result;
        }
    }
}

您也可以按照 hakon 的回答推荐使用 CountDownLatch.它会做基本相同的事情.我还建议您熟悉 java.util.concurrent 包 以更好地管理线程.最后,仅仅因为您可以这样做并不能使它成为一个好主意.如果您正在使用基于异步回调的框架,那么学习如何有效地使用该框架可能比试图颠覆它要好得多.

You could also use a CountDownLatch as recommended by hakon's answer. It will do basically the same thing. I would also suggest you get familiar with the java.util.concurrent package for a better way to manage threads. Finally, just because you can do this doesn't make it a good idea. If you're working with a framework that's based on asynchronous callbacks, you're probably much better off learning how to use the framework effectively than trying to subvert it.

这篇关于在 Java 中处理异步响应的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆