Search code examples
javajersey-2.0

Jersey 2 resource needs to cleanup


I have a singleton resource that creates objects in its constructor, and when the application shuts down, and the server terminates, I need to release these objects. How is this done in Jersey 2?

@Path("/")
@Singleton
public class MyResource {
    private Map<String, MyObject> cache;

    public MyResource() {
        cache = new ConcurrentHashMap<>();
        // at some point I need to remove all entries
        // from the map and close all MyObject objects there
        //
        // the reason is because MyObject might have files open
        // and I need to close the files
        //
        // where can I do that?
    }
    ...
}

Solution

  • Jersey supports the @PreDestroy lifecycle hook. So just annotate a method in the class with @PreDestroy, and Jersey will call it before the resource is disposed

    import javax.annotation.PreDestroy;
    
    @Path("/")
    @Singleton
    public class MyResource {
        private Map<String, MyObject> cache;
    
        public MyResource() {
        }
    
        @PreDestroy
        public void preDestroy() {
            // do cleanup
        }
    }