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