3

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??

Chowdappa
  • 1,580
  • 1
  • 15
  • 31

1 Answers1

2

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:

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • What if multiple responses access String stTime = (String) requestContext.getProperty("StartTime"); ?? – Chowdappa Nov 11 '16 at 06:59
  • Thanks for quick response, I am thinking, filter() in response is not thread safe and stTime is Overriding by another response/thread while first thread calculating execution time at the bottom. – Chowdappa Nov 11 '16 at 07:14
  • 1
    Each request gets it's own ContainerRequest(Response)Context. So I am not following where you think this could possibly cause a problem – Paul Samsotha Nov 11 '16 at 07:24