Java
  Home arrow Java arrow Page 4 - Developing Your Servlet Skills
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Developing Your Servlet Skills
By: Murach Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 4
    2006-09-21

    Table of Contents:
  • Developing Your Servlet Skills
  • Other skills for working with servlets
  • How to code instance variables
  • How to code thread-safe servlets

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    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.

       · This article is an excerpt from the book "Murach's Java Servlets and JSP," published...
     

    Buy this book now. This article is excerpted from chapter five of the book Murach's Java Servlets and JSP, written by Andrea Steelman and Joel Murach (Murach; ISBN: 1890774189). Check it out today at your favorite bookstore. Buy this book now.

    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...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek