SERVLET and THREADLOCAL test

zhaozj2021-02-11  264

SERVLET and THREADLOCAL test

I haven't clear the variable life cycle in servlet very early.

Recently, Hibernate has recently involved THREADLOCAL.

Do a test to see the effective range of their variables

public class TestThreadServlet extends HttpServlet {private static ThreadLocal thread = new ThreadLocal (); private int flag = 0; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {flag ; String str = "This is the first String." New Object (); if (thread.get () == null) thread.set (STR); PrintWriter out = response.getwriter (); out.println ("

"); out.println ("< Br> flag: " flag); Out.println ("
sessionid: " Request.getSession (). GetId ()); out.println ("
servlet: " this.tostring ()) Out.println ("
thread:" thread.get ()); out.println ("");}}

Results of the:

Session 1: flag: 2 sessionid: amGeaiVwKvL9 servlet: test.other.TestThreadServlet@5f2db0 thread: This is the first String.java.lang.Object@1ad6b4b Session 1: flag: 3 sessionid: aR3GkcUQoXT- servlet: test.other.TestThreadServlet @ 5f2db0 thread: this is the first string.java.lang.Object@6214f5

It can be seen from the execution result.

1 Server only creates an instance for each servlet. Flag does not stop

2 The object in Threadlocal in the session range is unique. Different requests, Object's hashcode is the same.

3 Different sessions sharing threadlocal, but the internal object is different

Another: Later, someone reminded me that in fact, the same servlet is configured in Web.xml, which will be two different instances. That is, the instance of the servlet is related to the configuration.

转载请注明原文地址:https://www.9cbs.com/read-4935.html

New Post(0)