gpt4 book ai didi

java - ContainerRequestFilter 和 ContainerResponseFilter 线程安全吗?

转载 作者:行者123 更新时间:2023-11-30 08:31:44 26 4
gpt4 key购买 nike

我有下面的代码,它工作正常。我的问题是代码下面的天气是否是线程安全的。通过阅读 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 就可以线程安全了??

最佳答案

它已经是线程安全的了。 ResourceInfoHttpServletRequest 都是代理(使用本地线程),而 java.util.Logger 上的方法是线程安全的。

另见:

关于java - ContainerRequestFilter 和 ContainerResponseFilter 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40512692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com