Home arrow Java arrow Page 4 - Developing Your Servlet Skills
JAVA

Developing Your Servlet Skills


Last week, you learned how to create, save, and compile a servlet. This week, you will learn more about working with servlets, such as how to code thread-save servlets. This article, the second of three parts, is excerpted from chapter five of the book Murach's Java Servlets and JSP, written by Andrea Steelman and Joel Murach (Murach; ISBN: 1890774189).

Author Info:
By: Murach Publishing
Rating: 3 stars3 stars3 stars3 stars3 stars / 4
September 21, 2006
TABLE OF CONTENTS:
  1. · Developing Your Servlet Skills
  2. · Other skills for working with servlets
  3. · How to code instance variables
  4. · How to code thread-safe servlets

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Developing Your Servlet Skills - How to code thread-safe servlets
(Page 4 of 4 )

A thread-safe servlet, like a thread-safe JSP, is one that works correctly even if more than one servlet thread is running at the same time. To code a thread-safe servlet, you not only have to synchronize the use of any instance variables that could be corrupted, but also any methods that could cause problems if they were used by two or more threads at the same time.

In figure 5-8, you can see how to limit the use of code to a single thread at three different levels. First, you can synchronize a block of code by using the synchronized and this keywords. Second, you can synchronize an entire method. Third, you can use the SingleThreadModel interface to limit the use of an entire servlet to a single thread. That way, you don’t have to synchronize any of the code within the servlet.

As you code thread-safe servlets, you must remember that one thread has to wait while another thread is using a synchronized block of code, a synchronized method, or a single-thread servlet. Since that can affect the performance of a web application, your general goal should be to synchronize as little code as possible. As a result, synchronizing a block of code within a method is best for performance, synchronizing a method is next best, and coding single-thread servlets should usually be avoided.

But those decisions also depend on other factors like how long it takes to run a servlet or a method and how many users are likely to access a servlet at any given time. If the pages on your web site get accessed thousands of times each day, performance is obviously an issue. But if your web site gets only a few dozen visitors a day, performance may not be an issue at all.

A block of synchronized code

  synchronized(this){
      accessCount++;
      if (accessCount == 1000){
          LogUtil.logToFile("We reached 1000 users on "
                           
+ new java.util.Date());
     
}
  }

A synchronized method

  public static synchronized int addRecord(Connection connection, User user)
 throws SQLException{
    String query =
           "INSERT INTO User " + 
           "(EmailAddress, FirstName, LastName) " +
           "VALUES ('" + SQLUtil.encode(user.getEmailAddress()) + "', " +
                   
"'" + SQLUtil.encode(user.getFirstName()) + "', " +
                    "'" + SQLUtil.encode(user.getLastName()) + "')";
    Statement statement = connection.createStatement();
    int status = statement.executeUpdate(query);
    statement.close();
    return status;

  }

A servlet that prevents multiple thread access

  public class EmailServlet extends HttpServlet implements SingleThreadModel{…
}

Description

  1. A thread-safe servlet is one that works correctly when more than one thread is running at the same time.
  2. To synchronize access to a method or a block of code, you can use the synchronized keyword. Then, only one thread at a time can access the code in the block or the method.
  3. To prevent multiple threads from accessing the code in a servlet, you can implement the SingleThreadModel interface. This is a tagging interface that prevents two threads from accessing the servlet’s service method at the same time.

Note

  • A tagging interface is one that has no methods.

Figure 5-8   How to code thread-safe servlets

Please check back next week for the conclusion of this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...
- Generics and Limitations in Java
- Getting Started with Java Web Development in...

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials