Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ContainerRequestFilter and ContainerResponseFilter thread safe?

I have below code, it works fine. My question is weather below code is thread safe or not. By reading of Servlet Filter and Container*Filter concepts, I am confused.

How to make this filter as thread safe ?

 @Provider
public class ResourceLoggingFilter implements ContainerRequestFilter,   ContainerResponseFilter {

@Context
private ResourceInfo resourceInfo;

@Context
private HttpServletRequest  servletRequest;

@Inject
private java.util.logging.Logger logger;

public void filter(ContainerRequestContext requestContext,  ContainerResponseContext responseContext) throws IOException {
    String stTime = (String) requestContext.getProperty("StartTime"); 
    logger.log(Level.INFO,"<== Leaving Resource Path: "+ requestContext.getUriInfo().getPath());
    logger.log(Level.INFO,"<== Leaving Resource Method: "+  resourceInfo.getResourceMethod().getName());
    logger.log(Level.INFO,"<== Leaving Resource class: "+ resourceInfo.getResourceClass().getCanonicalName());
    logger.log(Level.INFO,"<== Leaving Session id: "+ servletRequest.getSession().getId());
    if (null == stTime || stTime.length() == 0) {
        logger.log(Level.INFO,"start-time not captured or cleared");
        stTime = "0";
    }
    long startTime = Long.parseLong(stTime);
    long executionTime = System.nanoTime() - startTime;
    logger.log(Level.INFO,"Total execution time : "+executionTime+" nano seconds."  );

}

public void filter(ContainerRequestContext requestContext) throws IOException {
    requestContext.setProperty("StartTime", String.valueOf(System.nanoTime())); 
    logger.log(Level.INFO,"==> Entering Resource Path: "+ requestContext.getUriInfo().getPath());
    logger.log(Level.INFO,"==> Entering Resource Method: "+  resourceInfo.getResourceMethod().getName());
    logger.log(Level.INFO,"==> Entering Resource class: "+ resourceInfo.getResourceClass().getCanonicalName());
    logger.log(Level.INFO,"==> Entering Session id: "+ servletRequest.getSession().getId());

}

}

EDIT Is it good to have private volatile String stTime; statement, So that stTime can be thread safe??

like image 482
Chowdappa Avatar asked Nov 07 '25 18:11

Chowdappa


1 Answers

It's already thread-safe. Both the ResourceInfo and the HttpServletRequest are proxies (using thread-locals), while the methods on java.util.Logger are thread-safe.

See aslo:

  • Jersey 2: filters and @Context injections
  • Request-scoped context field injections into RESTEasy singletons
like image 66
Paul Samsotha Avatar answered Nov 10 '25 16:11

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!