WriteListener (servlet 3.1) semantics
Asked Answered
D

2

6

Let's say I'm writing chunks of data to an HttpServletResponse. So my method receives an array of bytes, I write it to response.getOutputStream(), and then I release the thread. When I receive another chunk of data, my method will be awaken, and it will write to getOutputStream() again. In the end, I call to AsyncContext.complete().

Now, the WriteListener.onWritePossible() spec says:

this method will be invoked by the container the first time when it is possible to write data. The container will subsequently invoke the onWritePossible method if and only if isReady method on ServletOutputStream, described below, returns false.

It seems that when the container calls this method, I already need to have my response buffered somewhere, because onWritePossible() may never be called again. So, for the previous example, I need to write all chunks of data I receive in a buffer (a byte array, or maybe a temporary file if the buffer is big enough), and if onWritePossible() is called before my response is complete, what should I do? Block the thread until I have all my response data?

Deliverance answered 13/6, 2013 at 12:42 Comment(0)
V
1

Check code in following link. May not be the exact solution but it's idea can be a solution for your case: Servlet 3.1 Async IO Echo

Vouvray answered 26/12, 2015 at 6:45 Comment(0)
O
0

hmm.. Maintaining a buffer seems to be the way

    public void onWritePossible() throws IOException {
       doWrite();  
    }

    // this is some callback where you received next chunk of data
    public void onMoreDataReceived(byte[] data) {
      putDataToBuffer(data);
      doWrite();
    }

    // this method is non-blocking
    private void synchronized doWrite() throws IOException {
       while (_servletOutputStream.isReady() && hasMoreDataInBuffer()) {
         _servletOutputStream.write(getMoreBytesFromBuffer());
       }
    }
Odds answered 12/2, 2015 at 1:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.