Search code examples
javaasynchronousjettycontinuationsdropwizard

How do I use Jetty Continuations in Dropwizard?


I have a resource method that looks like this:

@Path("/helloworld")
@GET
public Response sayHello(@Context HttpServletRequest request)
        throws InterruptedException {
    Continuation c = ContinuationSupport.getContinuation(request);

    c.suspend();
    Thread.sleep(1000);
    c.resume();

    return Response.ok("hello world hard").build();
}

It seems that when I call this endpoint, dropwizard ends up calling the sayHello method in an infinite loop. Am I doing this correctly?


Solution

  • You would use the continuation like you would for any Jetty server. Something like this really contrived example:

    public Response sayHello(@Context HttpServletRequest request)
            throws InterruptedException {
      Continuation c = ContinuationSupport.getContinuation(request);
    
      c.setTimeout(2000);
      c.suspend();
    
      // Do work
      System.out.println("halp");
    
      // End condition
      if (c.isInitial() != true) {
        c.complete();
        return Response.ok().build();
      }
    
      return Response.serverError().build();
    }
    

    You go into an infinite loop because you are never getting to end of the block to return the response and the continuation is continually suspending/resuming.