我InheritableThreadLocal
在我的Servlet
课堂上使用。这样它就可以从它的子线程中获得。InheritableThreadLocal
在线程池执行程序中使用是邪恶的吗?. 比如servlet线程池。
我的问题。
1) 为什么我们要避免InheritableThreadLocals
在 servlet 中使用?
2)这种内存泄漏是否可能发生在InheritableThreadLocal
?
3) 有什么替代方法InheritableThreadLocal
吗?
4)如果线程被重用,存储的值threadlocal
不会被清除会怎样?
我的实时场景
public class UserAccessFilter implements javax.servlet.Filter {
static final InheritableThreadLocal<String> currentRequestURI = new InheritableThreadLocal<String>();
public void doFilter(ServletRequest req, ServletResponse resp , FilterChain fc) throws IOException, ServletException{
String uri = request.getRequestURI();
fc.doFilter(request, response);
}
}
public class MailServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mailCount = req.getParameter("mailCount");
if(mailCount != null && !"".equals(mailCount) && mailCount.matches("[0-9]+")){
MailThread mailThread = new MailThread("xxx@gmail.com", generateToAddress(Integer.parseInt(mailCount))); //NO I18N
Thread t = new Thread(mailThread);
t.start();
}
resp.getWriter().println("Mail Servlet.............."); //NO I18N
}
}
class MailThread implements Runnable{
private String from;
private String to;
public MailThread(String from , String to){
this.from = from;
this.to = to;
}
@Override
public void run() {
sendMail();
}
public void sendMail(){
//I want this uri from child threads. I can't pass this value to this constructor.
String uri = currentRequestURI.get();
//Do Mail Operations
}
}
过滤器 --> Servlet A --> 子线程 ---> 邮件线程(这里我得到了过滤器中设置的值)。