Learn about thread safety of notes

  • 2020-05-07 19:52:13
  • OfStack

Before we talk about thread safety in struts2, let's say 1. What is thread safety ? This is a net friend said.

If your code is in a process that has multiple threads running at the same time, those threads might run the code at the same time. If the result of each run and the result of a single thread run is 1, and the value of other variables is also 1 as expected, it is thread-safe.

That is to say, in the process of 1 process has more than one thread concurrent execution, each thread execution process, the variable value is the same, the execution result is the same, is thread safety.

Since servlet is a singleton mode, only one instance will be generated. When multiple users request one servlet at the same time,Tomcat will send out multiple threads to execute the code of servlet. Therefore, servlet is not thread safe.


package com.wang.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ThreadSafeServlet extends HttpServlet {

  private String name;// define 1 Public private variables  name
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    // from request Domain to obtain name attribute 
    name =request.getParameter("name");
    // Put a thread to sleep 10 seconds 
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // Output to the browser name The value of the 
    response.getWriter().print("name="+name);
  }

} 

We access ThreadSafeServlet in 10 seconds using two browsers. name = "zhangSan" and ThreadSafeServlet & # 63; name = "liSi", according to the results are name = liSi, this means that there is a problem program, multi-threaded concurrent read-write leads to data synchronization problem, so we try not to define global when using servlet private property, but to define variables respectively to doGet () and doPost () method, of course, if just read operation, is there is no problem, so if you want to define global in servlet read-only property is best defined as final type.

Action in Struts2 creates one instance for each request,Action is no different from the regular java class, there is no data out of sync, so it is thread-safe.
The above is the entire content of this article, I hope to help you with your study.


Related articles: