我在我的Servlet
類中使用了InheritableThreadLocal
。以便它可以從它的子線程中獲得。在線程池執行程序中使用InheritableThreadLocal
是否是這種罪惡? 。比如servlet線程池。爲什麼我應該避免在servlet中使用InheritableThreadLocal?
我的問題。
1)爲什麼我們應該避免在servlets中使用InheritableThreadLocals?
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("[email protected]", 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 - >子線程--->郵件線程(在這裏我得到的過濾器設置好的值)。
我無法將requestURI傳遞給'MailThread'。在這裏我發佈示例場景。 – kannanrbk
爲什麼你可以將requestURI傳遞給'MailThread',在'doGet'方法中有'HttpServletRequest'? –
是的,但我不能限制發送請求的uri發送電子郵件。它可以被其他成員使用。 – kannanrbk