Asynchronous ContainerRequestFilter using ManagedAsync
A ContainerRequestFilter cannot be executed asynchronously.
A very common use case for this filter would be an authorization check, but if that check goes to an external service or to a database, benefits from @ManagedAsync are lost because only resource methods are invoked asynchronously.
This is very tricky because a PreMatching filter could change the request from a @ManagedAsync resource method to a non-async method, or visa-versa. Maybe any filters that are not PreMatching should be offloaded to the ExecutorService if the matching resource method has @ManagedAsync? Or maybe an entirely new type of filter should be introduced for this case, one that's basically an HK2 AOP MethodInterceptor?
- Issue Imported From: https://github.com/jersey/jersey/issues/2596
- Original Issue Raised By:@glassfishrobot
- Original Issue Assigned To: @mpotociar
@glassfishrobot Commented Reported by aldenquimby
@glassfishrobot Commented aldenquimby said: StackOverflow question about this: http://stackoverflow.com/q/20556200/1415732
@glassfishrobot Commented aldenquimby said: I've tried a lot of things to get around this problem, and found one really hacky solution.
Guice AOP - failed Though I got Guice injection working with Jersey 2.5 (a feat in itself!), I could not get Guice to create the resource classes, so AOP does not work on resource methods. This is a well known problem.
HK2 AOP - failed HK2 just recently released this feature, and it appears Jersey does not support this yet because I could not get it working. I'm waiting on an answer to this stackoverflow comment before pursuing this farther.
Monitoring - worked Registering an ApplicationEventListener that calls my authorization service on RequestEvent RESOURCE_METHOD_START appears to work. This event is triggered by the ManagedAsync thread, which is what I need. Though this works, it is clearly unsafe, as the Jersey docs say to only use event listening for monitoring, and not any actual work.
@glassfishrobot Commented aldenquimby said: UPDATE
I got this working with HK2's AOP. You can see roughly what I did here: http://stackoverflow.com/q/22275562/1415732.
I've since expanded my solution, and added a registerAsyncFilter to my implementation of ResourceConfig. This registers the filter with my bound HK2 InterceptionService, which runs the filter as a MethodInterceptor right before the method is invoked. Unlike normal ContainerRequestFilter's, these are now run on the @ManagedAsync thread created by Jersey, which is exactly what I need.
I would be happy to share more of my solution if anyone else is struggling with a ContainerRequestFilter and @ManagedAsync.
@glassfishrobot Commented This issue was imported from java.net JIRA JERSEY-2324
@Anish841 Commented I am also facing same issue . What is the recommended way to approach this issue ?
Any update here?