Monday, December 26, 2011

How does servlet instances share variable instances in a servlet container

On my post about Java class loader and static variable, I was asked if a static member shared for all user of a web application?

The quick answer is Yes. A static variable in a class used in a Servlet will be shared by all users who access the same application. However, to be precisely, A static member of class used in Servlet class will be shared by all instances of that servlet class. It is not just all user (or user's request). One servlet can be configured to have multiple instances in servlet engine.

If we only want to share variable among different user access to one servlet instance, we do not need to declare it as static. We can simply put it as global variable in our servlet class. This is actually topic about thread safe servlet programming.

We can also store variable in ServletContext if we want to share variable among different instances of servlet and it does not matter for other servlets in same context to see it.

Below is code to determine how static variable act inside servlet.

Step 1, Create a dummy class having static field.
/**
 *
 * @author Yiyu Jia
 */
public class DummyClass {
    //declare a static member.
    //This variable will be used as counter.
    static int jia = 0;    
}

Step 2, Create a servlet to validate variable values.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Yiyu Jia
 */
public class TestStaticServlet extends HttpServlet {

    static int classCount = 0;  // shared by all servlet instances
    int count = 0;              // separate for each servlet
    static Hashtable instances = new Hashtable();  // also shared

    DummyClass jia = new DummyClass();

    /** 
     * Processes requests for both HTTP GET and POST methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            jia.jia++;
            count++;
            out.println("Since loading, this servlet instance has been accessed "
                    + count + " times.
" );

            // Keep track of the instance count by putting a reference to this
            // instance in a Hashtable. Duplicate entries are ignored.
            // The size() method returns the number of unique instances stored.
            instances.put(this, this);
            out.println("There are currently "
                    + instances.size() + " instances.
");

            classCount++;
            out.println("Across all instances, this servlet class has been "
                    + "accessed " + classCount + " times.
");

            out.println("jia static value:  " + jia.jia + "
");

        } finally {
            out.close();
        }
    }

    // 
    /** 
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// 
}

Step 3: Configure two instance for one servlet in web.xml

    
        TestStaticServlet
        TestStaticServlet
    
    
        TestStaticServlet
        /TestStaticServlet
    
    
        TestStaticServlet2
        TestStaticServlet
    
    
        TestStaticServlet2
        /TestStaticServlet2
    
    
        
            30
        
    
    
        index.jsp
    


Step 4: Now, we can deploy and access two different instance throw web browser.
URL one: http://localhost:8080/ServletStatic/TestStaticServlet

URL two: http://localhost:8080/ServletStatic/TestStaticServlet2

Step 5: We see something like below as result in web browser

Monday, December 19, 2011

Seven ways to stored data in local through Web application.

To develop Web application, especially for mobile web application, one question is often asked is how can I store data in local. Particularly, how can we store large size of data in local disk? My answer is there should be no problem to do this. There must be technique to solve this issue as there are demand from market. This post is a collection of local storage methods, which I can think so far.

  1. HTTP cookies All developers know that HTTP cookies is designed to allow Web developer to store some data on browser side. But, it is also well know that its size limitation is small. The very cookies' maximum size could be different among different browsers. Maximum number of cookies may be different among different browsers. Using the number limitation of cookies per domain, we may find way to enlarge the imitation by deploy Web application among several servers having different Sub domain name.
  2. Flah player Because of mean of cookie, web developer go to Flah player for larger local storage size. By default, Flash player embedded in a Browser has 1MB limitation of local storage. But, user can adjust it until unlimited. Ext JS 3.x uses Flash local storage too.
  3. bookmarklet Since bookmarklet store javascript code locally, I can think that we can use it to pursue certain degree of local storage capability.
  4. Web Cache By configure Web server, we can ask browser to cache certain content on client side. Here is an example from Sencha web site:
    Taking Sencha Touch Apps Offline
  5. HTML 5 local storage A good news from HTML 5 is that HTML 5 compatible browser may support HTML 5 local storage. Its W3C recommended size limitation is 5M but some browser allow it be expandable.
  6. Web SQL database To have even larger local storage, we can use Web SQL database. Here is a list of When can I use Web SQL Database?. Here is an example usage: http://rem.im/html5-tweet-time-range.html
  7. Using Web browser wrapper Titanium and phoneGap are two popular web browser wrapper on mobile devices. Using this kind technology, the local storage space goes to almost unlimited.


Thursday, December 8, 2011

java vs php benchmark (cited from The Computer Language Benchmarks Game )

I saw a benchmark between Java 7 and PHP. I do not know how precisely the benchmark is. But, I will believe this result. Besides running speed and memory usage, there are many other factors affect us to choose Java or PHP as programming language. But, it is always interesting and valuable to be able to have a rough idea about this kind comparison.

Below is cited from http://shootout.alioth.debian.org/ . Interested can go there for detail.

This chart shows 3 comparisons - Time-used, Memory-used and Code-used ~ speed and size.
Each chart bar shows, for one unidentified benchmark, how much the fastest Java 7 -server program used compared to the fastest PHP program.