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

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

问题描述

我读了类似的Q&放答案; A

<一个href=\"http://stackoverflow.com/questions/3142915/how-do-you-create-an-asynchronous-http-request-in-java\">How你在Java中创建一个异步HTTP请求?|
<一href=\"http://stackoverflow.com/questions/6303753/asynchronous-programming-design-pattern\">Asynchronous程序设计模式的|结果
<一href=\"http://stackoverflow.com/questions/5058661/asynctask-android-design-pattern-and-return-values\">AsyncTask Android的 - 设计模式和返回值

我看到了很多的解决方案,但没有真正satifies我。

监听方式

在结果被捕获时,处理在onResult方法实施。

 公共接口GeolocationListener {
公共无效onResult(地址[]地址);
公共无效onerror的(例外五);
}

这个解决方案并不十分satify我,因为我要处理的主要方法的结果。我恨这个接口,因为返回的响应时,它在onResult导致加工链并没有办法回去主的方法进行处理。

这个servlet方式

 公共类SignGuestbookServlet这个延伸的HttpServlet {    公共无效的doPost(HttpServletRequest的REQ,HttpServletResponse的RESP)
                抛出IOException
        // ...
        resp.sendRedirect(/ guestbook.jsp);
    }
}

有没有公开的Java code调用这个servlet。所有的配置在web.xml完成​​

我想要的方式

等待这样的回应

 响应A = GETRESPONSE();
//等待,直到接收到响应,不要再进一步
//过程
响应B = GETRESPONSE();
//等待,直到接收到响应,不要再进一步
处理(A,B);

有一个设计模式来处理异步请求,并等待像上面的反应?比监听其他方式。
请没有图书馆或框架。

修改
由于迄今的反应。我没有给你的全貌,所以我接触Geolocation类
我开始实施。我不知道如何实现的方法。有人可以显示如何?他(或她)还必须实现监听器检索结果

 私有地址getFullAddress(字符串文本,AddressListener监听器,...){    //新的Geolocation(文字,监听器,选项)。开始()
    //实现Geolocation.GeolocationListener
    //如何返回从onResult地址?
}


解决方案

异步code可以随时进行同步。最简单的/最原始的办法是使异步调用,然后进入一个while循环,只是睡当前线程,直到值回来。

编辑: code时,将异步回调到同步code - 再次,原油实现:

 进口java.util.concurrent中*。公共类MakeAsynchronous $ C $ {cSynchronous
    公共静态无效的主要(字串[] args)抛出异常{
        最终监听器监听=新监听器();
        可运行DelayedTask的=新的Runnable(){
            @覆盖
            公共无效的run(){
                尝试{
                    视频下载(2000);
                }赶上(InterruptedException的E){
                    抛出新IllegalStateException异常(不应该被打断,E);
                }
                listener.onResult(123);            }
        };
        的System.out.println(System.currentTimeMillis的()+:启动任务);
        。Executors.newSingleThreadExecutor()提交(DelayedTask的);
        的System.out.println(System.currentTimeMillis的()+:等待任务完成);
        而(!listener.isDone()){
            视频下载(100);
        }
        的System.out.println(System.currentTimeMillis的()+:任务完成;结果=+ listener.getResult());
    }    私有静态类侦听器{
        私人整数结果;
        私人布尔做的;        公共无效onResult(整数结果){
            this.result =结果;
            this.done = TRUE;
        }        公共布尔isDone(){
            返回完成的;
        }        公共整数的getResult(){
            返回结果;
        }
    }
}

您也可以使用的CountDownLatch所推荐的哈孔伯爵的回答。这将基本上做同样的事情。我也建议你熟悉的为更好的方式来管理线程java.util.concurrent包。最后,只是因为你的可以的做到这一点并不能使一个好主意。如果你与是基于异步回调的框架工作,你可能先学习如何有效地使用该框架比试图颠覆它好多了。

I read answers from similar Q&A

How do you create an asynchronous HTTP request in JAVA? | Asynchronous programming design pattern |
AsyncTask Android - Design Pattern and Return Values

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

Listener way

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);
}

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.

The servlet way

public class SignGuestbookServlet extends HttpServlet {

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

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

The way I want

Wait for the response like this

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.

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 ?
}

解决方案

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.

Edit: 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;
        }
    }
}

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天全站免登陆