Write thread-safe JSP applications

Source: Internet
Author: User

JSP is executed in multiple threads by default. This is different from ASP, PHP, PERL, and other scripting languages. It is also one of its advantages. However, if you do not pay attention to the synchronization problem in multiple threads, this will make the JSP program hard to discover errors. The following is an example of multithreading in JSP and its solution.

I. multithreading in JSP:

When the CLIENT requests a JSP file for the first time, the server compiles the JSP file into a CLASS file, creates an instance of this CLASS, and then creates a thread to process CLIENT requests. If multiple clients request the JSP file at the same time, the server creates multiple threads. Each client request corresponds to a thread. Multi-threaded execution can greatly reduce system resource requirements and increase the concurrency and response time of the system. The possible variables in JSP are described as follows:

Instance variables

Instance variables are allocated in the heap and shared by all the threads of the instance, so they are not thread-safe.

The JSP system provides eight class variables. The OUT, REQUEST, RESPONSE, SESSION, CONFIG, PAGE, and PAGECONXT used in JSP are thread-safe, and the APPLICATION is used throughout the system, so it is not thread-safe.

Local variable

Local variables are allocated in the stack. Because each thread has its own stack space, it is thread-safe.

Static class

Static classes can be directly used without being instantiated, and are not thread-safe.

External resources:

In a program, multiple threads or processes may simultaneously operate on the same resource (for example, multiple threads or processes simultaneously perform write operations on a file). At this time, pay attention to the synchronization problem.

Ii. multithreading in the following example:

<% @ Page import ="
Javax. naming .*,
Java. util .*,
Java. SQL .*,
Weblogic. common .*
"%>
<%
String name
String product;
Long quantity;
Name = request. getParameter ("name ");
Product = request. getParameter ("product ");
Quantity = request. getParameter ("quantity");/* (1 )*/
Savebuy ();
%>
<%!
Public void savebuy ()
{
/* Perform database operations and save the data to the table */
Try {
Properties props = new Properties ();
Props. put ("user", "scott ");
Props. put ("password", "tiger ");
Props. put ("server", "DEMO ");
Driver myDriver = (Driver) iver "). newInstance ();
Conn = myDriver. connect ("jdbc: weblogic: oracle", props );
Stmt = conn. createStatement ();
String inssql = "insert into buy (empid, name, dept) values (?, ?, ?,?) ";
Stmt = conn. prepareStatement (inssql );
Stmt. setString (1, name );
Stmt. setString (2, procuct );
Stmt. setInt (3, quantity );
Stmt.exe cute ();
}
Catch (Exception e)
{
System. out. println ("SQLException was thrown:" + e. getMessage ());
}
Finally // close connections and {
Try {
If (stmt! = Null)
Stmt. close ();
If (conn! = Null)
Conn. close ();
} Catch (SQLException sqle ){
System. out. println ("SQLException was thrown:" + sqle. getMessage ());
}
}
}
%>

The above program simulates a part of online shopping and saves the user name, purchased item name, and quantity entered by the user in the browser to the table BUY. Instance variables are used in the savebuy () function, so it is not thread-safe. Because: each statement in the program is not an atomic operation, such as name = request. getParameter ("name"); multiple machine commands are generated during execution, and may be transferred to sleep due to system scheduling at any time, so that other threads can continue to execute. If thread A is in sleep state when it is executed to (1), thread B starts to execute and changes the value of QUANTITY. When it is executed to thread A again, it will call savebuy () the function is executed, so that the QUANTITY saved to the table is the value modified by thread B. Then, the actual number of users purchased by thread A is inconsistent with the data kept in the table, this is a serious problem.

Iii. Solution

Single-threaded

Add: To the JSP file so that it is executed in a single thread. At this time, there is only one instance, and all client requests are executed in a serial way. This will reduce the system performance.

The savebuy () function and synchronized are used for thread synchronization. the JSP is still executed in multiple threads, but the system performance is also reduced:

Public synchronized void savebuy ()
{
......
}

Use local variables instead of instance variables. The savebuy () function is declared as follows:

Because savebuy () uses the passed parameters and is allocated in the stack, It is thread-safe.

Public void savebuy (String name, String product, int quantity)
{
......
}

The call method is changed:

<%
String name
String product;
Long quantity;
Name = request. getParameter ("name ");
Product = request. getParameter ("product ");
Quantity = request. getParameter ("quantity ");
Savebuy (name, product, quantity)
%>

If savebuy has many parameters or the data needs to be used in many places, you can declare a class and use it as a parameter, for example:

Public class buyinfo
{
String name;
String product;
Long quantity;
}
Public void savebuy (buyinfo info)
{
......
}

The call method is changed:

<%
Buyinfo userbuy = new buyinfo ();
Userbuy. name = request. getParameter ("name ");
Userbuy. product = request. getParameter ("product ");
Userbuy. quantity = request. getParameter ("quantity ");
Savebuy (userbuy );
%>

 

So it is best to use 3, because 1 and 2 will reduce the system performance.

Multithreading is generally possible only when there is a large amount of concurrent access, and it is difficult to repeat, so you should always pay attention to it during programming.

Related Article

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.