Jersey supports org.glassfish.jersey.server.CloseableService that lets you 
register Closeable objects to be closed when the request is complete:

public Response streamData(..., @Context CloseableService closer) {
  ...
  closer.add(closeable);
  return Response.ok(...).build();
}



On Friday, March 1, 2019 at 3:10:26 PM UTC-6, Matthias Müller wrote:
>
> Hi,
>
> I'm looking for a robust mechanism to close Resources that have been 
> opened within a request scope. My application streams lots of data from a 
> backend and that connection remains open until it is acively closed. 
> Sometimes I spot resource leaks and suspect that they are caused by aborted 
> requests. This is the code I use:
>
>  @GET
>
>  //@Produces(...)
>  public Response streamData(...) {    ...
>     Stream<Pojo> ps = null;
>     try {
>         // connect to db and obtain data stream for <key>
>         ps = loadData(db, key);
>         // apply detailed encoding instrunctions and create a StreamingOutput
>         final StreamingOutput stream = Encoder.encodeData(ps, encodingArgs);
>         return Response.ok(stream).build();
>     } catch (Exception e) {
>         closeOnException(ps); // wrapper for ps.close();
>         throw e;
>     }
>  } 
>
>
> What it handles are exceptions that occur *before* the Response is built, 
> but I can hardly control what happens afterwards. So I am looking for a 
> bullet-proof mechanism or hook that allows me to close any resources that 
> were opened within the request scope. @UnitOfWork is a mechanism that is 
> very close to what I want, but it is closely coupled to Hibernate. What I 
> need is a hook that accepts any instance of Closeable/Autocloseable that is 
> used within the executed method.
>
> -Matthias
>

-- 
You received this message because you are subscribed to the Google Groups 
"dropwizard-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to