Can a RESTful Web Service return a POST Response from Child Thread?

时间:2016-07-11 20:04:28

标签: java multithreading rest httpresponse

Currently this is the implementation I have for the incoming POST Request. The processing is handled by a Child Thread, but the response must be returned back to the top level to send a response.

@Post("json")
public String POSTMessage(String myJsonString) throws Exception {
    JSONObject msg = (JSONObject) new JSONParser().parse(myJsonString);
    ClassA Client = new ClassA();
    Server.client_list.add(Client);

    return Client.processMSG(msg);
}

ClassA Processing builds a JSON Response and returns that to Top Level. Is there any way the Child Thread could send the response back in a Restful architecture? In other words, does the POSTmessage function need to return the value, or is there some way a Child Thread can respond as the POSTMessage can go back to listening on a port.

1 个答案:

答案 0 :(得分:0)

You can use asynchronous response, like:

@Post("json")
public void POSTMessage(String myJsonString, @Suspended final AsyncResponse asyncResponse) throws Exception {
    new Thread(new Runnable() {
        @Override
        public void run() {
           JSONObject msg = (JSONObject) new JSONParser().parse(myJsonString);
           ClassA client = new ClassA();                
           asyncResponse.resume(client.processMSG(msg));
        }
    }).start();
}