Q:

Java Servlet - Observer Pattern causing null Response object

I have a Java HttpServlet. This servlet contains a set of objects that make use of the observer pattern in order to return data through the servlet's Response object. Here is a simplified version of my doGet() method in the HttpServlet:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
    MyProcess process = new MyProcess();
    // This following method spawns a few threads, so I use a listener to receive a completion event.
    process.performAsynchronousMethod(request, new MyListener() {
        public void processComplete(data) {
            response.getWriter().print(data.toString());
        }
    }
}

As the example shows, I have a process that I execute, which spawns a variety of threads in order to produce a final dataset. This process can take anywhere from seconds to a minute. My problem is, it appears that as the doGet() method completes, the response object becomes null. When processComplete() is called, the response object will be null - thus preventing me from writing any data out. 
It appears as if the servlet is closing the connection as soon as the asynchronous method is called. 
Is there a better way to implement this type of servlet when using the observer pattern for asynchronous tasks? Should I do this in another way?

A:

The servlet response will be sent back to the client when the doGet method terminates, it won't wait for your asynchronous call to finish as well. You will need to find a way to block until all your asynchronous tasks have completed, and only then allow the doGet() method to return.
The answers to this question should point you in the right direction.
Something else to watch out for is that you have no guarantee that the threads will write to the response writer in series, you may find that the various print operations overlap and the output will be garbled (this may not matter to you, depending on what the data is, and how it will be used)

