我有以下代码,它工作正常。我的问题是代码下面的天气是否是线程安全的。通过阅读Servlet Filter和Container * Filter概念,我很困惑。
如何使此过滤器成为线程安全的?
@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());
}
}
修改
有private volatile String stTime;
语句是好的,所以stTime可以是线程安全的吗?
答案 0 :(得分:2)
它已经是线程安全的。 ResourceInfo
和HttpServletRequest
都是代理(使用线程本地),而java.util.Logger上的方法是线程安全的。
请参阅: