Thread Safety for Servlets

Source: Internet
Author: User

Thread safety for Servlets One, what is servlet thread safety

1. In The construction method is only executed once for the entire life cycle of the servlet. That is, there is only one servlet instance object in the entire life cycle of the servlet. This indicates that the servlet is a single-threaded, and may cause thread-safety issues.

The so-called thread safety is a The servlet instance object handles multiple requests at the same time, so the servlet is really high-productivity. However, if the servlet contains member variables, it is possible for one thread to write to the member variable, while another thread reads the member variable. Therefore, a single multithreaded servlet cannot create a member variable.

Below I'll take an example to discuss thread safety issues ( No code for thread safety issues :)

1 Package Gacl.servlet.study;2 3 import java.io.IOException;4 5 import javax.servlet.ServletException;6 import Javax.servlet.http.HttpServlet;7 import javax.servlet.http.HttpServletRequest;8 import Javax.servlet.http.HttpServletResponse;9   Ten         /** One * Is there a thread-safety issue when multithreading concurrently accesses the code inside this method?? A * I variables are accessed concurrently by multiple threads, but there is no thread safety problem, because I is a local variable inside the Doget method, - * When there are multiple threads accessing the Doget method concurrently, each thread has its own I variable, - * Each thread is operating its own I variable, so there is no thread safety issue the * Multithreading concurrent access to a method, if some resources (variables, collections, etc.) are defined inside the method - * Then every thread has these things, so there's no thread-safety problem. -          */ - Public class Servletthread extends HttpServlet { +  -      + Public void Doget (HttpServletRequest request, httpservletresponse response) A throws Servletexception, IOException { at int a=1; - a++; - response.getwriter (). write (a); -     } -  - Public void DoPost (HttpServletRequest request, httpservletresponse response) in throws Servletexception, IOException { - doget (request, response); to     } +  -}

Code that has thread safety issues:

1  PackageGacl.servlet.study;2 3 Importjava.io.IOException;4 5 Importjavax.servlet.ServletException;6 ImportJavax.servlet.http.HttpServlet;7 Importjavax.servlet.http.HttpServletRequest;8 ImportJavax.servlet.http.HttpServletResponse;9 Ten  Public classServlettreaddemoextendsHttpServlet { One  A     intI=1; -      Public voiddoget (httpservletrequest request, httpservletresponse response) -             throwsservletexception, IOException { thei++; -         Try { -Thread.Sleep (1000*3); -}Catch(interruptedexception e) { + e.printstacktrace (); -         } +Response.getwriter (). Write (i+ ""); A     } at  -      Public voidDoPost (httpservletrequest request, httpservletresponse response) -             throwsservletexception, IOException { - doget (request, response); -     } -  in}

When I is defined as a global variable, and multiple threads concurrently access the variable global variable I, there is a thread safety problem, if you open two browsers simultaneously to simulate concurrent access to the same servlet, the first browser should normally see 2, and the second browser should see 3, As a result, two browsers saw 3.

2. Solutions to thread safety issues:

1. Locking (synchronized)

When synchronized is added, there is no thread safety problem when accessing I concurrently, why is there no thread safety problem after adding synchronized? If there is a thread accessing the Servlet object now, it will first get the lock of the Servlet object and wait until it is executed before returning the lock back to the Servlet object, because it first gets the lock of the Servlet object, So when there are other threads accessing the Servlet object, because the lock has been taken away by the previous thread, the thread behind it can only wait. This is unscientific. If there are 1000 people visiting ServletThreadDemo1 at the same time . The people in the back still can't wait to vomit blood!!

1  PackageGacl.servlet.study;2 3 Importjava.io.IOException;4 5 Importjavax.servlet.ServletException;6 ImportJavax.servlet.http.HttpServlet;7 Importjavax.servlet.http.HttpServletRequest;8 ImportJavax.servlet.http.HttpServletResponse;9 Ten  One  Public classServletThreadDemo1extendsHttpServlet { A  -     intI=1; -      Public voiddoget (httpservletrequest request, httpservletresponse response) the             throwsservletexception, IOException { -         synchronized(ServletThreadDemo1.class) {//in Java, each object has a lock, and this here refers to the Servlet object -i++; -             Try { +Thread.Sleep (5000*2); -}Catch(interruptedexception e) { + e.printstacktrace (); A             } atResponse.getwriter (). println (i+ ""); -         } -          -     } -  -      Public voidDoPost (httpservletrequest request, httpservletresponse response) in             throwsservletexception, IOException { - doget (request, response); to     } +}

2.sun The solution is: If a servlet implements the Singlethreadmodel interface, the servlet engine invokes its service method in single-threaded mode. No method is defined in the Singlethreadmodel interface, as long as the declaration of implementing the Singlethreadmodel interface is added to the definition of the servlet class. The Servlet,servlet engine, which implements the Singlethreadmodel interface, still supports multithreaded concurrent access to the servlet by producing multiple servlet instance objects. Each concurrent thread invokes a separate Servlet instance object. But implementing the Singlethreadmodel interface does not really address the threading security of the servlet, because the servlet engine creates multiple servlet instance objects. The real problem with multithreading security is that a Servlet instance object is called simultaneously by multiple threads. In fact, in servlet API 2.4, Singlethreadmodel has been marked as deprecated (obsolete).

Thread Safety for Servlets

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.