Monday 8 September 2014

WriteListener

To process a servlet request, Servlet container uses the server thread. To make Application high available, you must ensures that the threads handling the request are not sitting idle. Lets take a scenario, server sending large amounts of data to the client. Due to network delays or some other reasons, client may not read the data as fast as server can send. In these situations the thread used to process this request some times sits idle (waiting for client to read the data).

There is a solution with Asynchronous processing. For more information about Asynchronous processing, follow the below link.


Asynchronous processing using WriteListener
It supports non blocking write mechanism for servlet and filters in asynchronous mode.
Method Description
onError(Throwable t) Invoked when an error occurs writing data using the non-blocking APIs.
onWritePossible() A ServletOutputStream instance calls these methods on its listener when it is possible to write data without blocking

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.util.concurrent.*;
import java.util.*;

@WebServlet(urlPatterns = {"/WriteListenerEx"}, asyncSupported=true)
public class WriteListenerEx extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
        final AsyncContext acontext = req.startAsync();
        final ServletOutputStream outStream= res.getOutputStream();
        final Queue<Integer> myList = new LinkedBlockingQueue<>();
        
        for(int i=0; i<100000; i++){
            myList.add(i);
        }
        
        outStream.setWriteListener(new WriteListener(){
            int count = 0;
            
            @Override
            public void onWritePossible() throws IOException{
                System.out.println("Write possible");
                while(outStream.isReady() && myList.size() > 0){
                   outStream.print(myList.poll());
                }   
            }
            
            @Override
            public void onError(Throwable t){
                
            }
        });
        
        System.out.println("Container thread back to pool");
    }   
}

Below messages appear in server console file.

Info:   Container thread back to pool
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible
Info:   Write possible




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment