Wednesday, January 29, 2014

Class Loading in detailed

This is part 4 of our “Exception in thread main java.lang.NoClassDefFoundError” troubleshooting series. As you saw from my previous articles, missing Jar files and failure of static initializers are the most common sources of this problem. However, sometimes the root cause is due to a more complex Java class loader problem which is quite common when developing Java EE applications involving multiple parent and child class loaders. The following article will describe one common problem pattern when using the default class loader delegation model.
A simple Java program will again be provided in order to help you understand this problem pattern.
Default JVM Classloader delegation model
As we saw from the first article, the default class loader delegation model is from bottom-up e.g. parent first. This means that the JVM is going up to the class loader chain in order to find and load each of your application Java classes. If the class is not found from the parent class loaders, the JVM will then attempt to load it from the current Thread context class loader; typically a child class loader.
NoClassDefFoundError problems can occur, for example, when you wrongly package your application (or third part API’s) between the parent and child class loaders. Another example is code / JAR files injection by the container itself or third party API’s deployed at a higher level in the class loader chain.

In the above scenarios:
  • The JVM loads one part of the affected code to a parent class loader (SYSTEM or parent class loaders)
  • The JVM loads the other parts of the affected code to a child class loader (Java EE container or application defined class loader)
Now what happens when Java classes loaded from the parent attempt to load reference classes deployed only to the child classloader? NoClassDefFoundError!
Please remember that a parent class loader has no visibility or access to child class loaders. This means that any referencing code must be found either from the parent class loader chain (bottom-up) or at the current Thread context class loader level; otherwise java.lang.NoClassDefFoundError is thrown by the JVM.
This is exactly what the following Java program will demonstrate.
Sample Java program
The following simple Java program is split as per below:
  • The main Java program NoClassDefFoundErrorSimulator is packaged in MainProgram.jar
  • A logging utility class JavaEETrainingUtil is packaged in MainProgram.jar
  • The Java class caller CallerClassA is packaged in caller.jar
  • The referencing Java class ReferencingClassA is packaged in referencer.jar
These following tasks are performed:
  • Create a child class loader (java.net.URLClassLoader)
  • Assign the caller and referencing Java class jar files to the child class loader
  • Change the current Thread context ClassLoader to the child ClassLoader
  • Attempt to load and create a new instance of CallerClassA from the current Thread context class loader e.g. child
  • Proper logging was added in order to help you understand the class loader tree and Thread context class loader state
It will demonstrate that a wrong packaging of the application code is leading to a NoClassDefFoundError as per the default class loader delegation model.
** JavaEETrainingUtil source code can be found from the article part #2
#### NoClassDefFoundErrorSimulator.java
package org.ph.javaee.training3;
import java.net.URL;
import java.net.URLClassLoader;
import org.ph.javaee.training.util.JavaEETrainingUtil;
/**
 * NoClassDefFoundErrorSimulator
 * @author Rafi
 *
 */
public class NoClassDefFoundErrorSimulator {
       
        /**
         * @param args
         */
        public static void main(String[] args) {
              
               System.out.println("java.lang.NoClassDefFoundError Simulator - Training 3");
               System.out.println("Author: Rafi Syed");
               System.out.println("http://javasoulution.blogspot.in/");
              
               // Local variables
               String currentThreadName = Thread.currentThread().getName();
               String callerFullClassName = "org.ph.javaee.training3.CallerClassA";
              
               // Print current ClassLoader context & Thread
               System.out.println("\nCurrent Thread name: '"+currentThreadName+"'");
               System.out.println("Initial ClassLoader chain: "+JavaEETrainingUtil.getCurrentClassloaderDetail());
              
               try {
                       // Location of the application code for our child ClassLoader
                       URL[] webAppLibURL = new URL[] {new URL("file:caller.jar"),new URL("file:referencer.jar")};
                      
                       // Child ClassLoader instance creation              
                       URLClassLoader childClassLoader = new URLClassLoader(webAppLibURL);
                      
                       /*** Application code execution... ***/
                      
                       // 1. Change the current Thread ClassLoader to the child ClassLoader
                       Thread.currentThread().setContextClassLoader(childClassLoader);
                       System.out.println(">> Thread '"+currentThreadName+"' Context ClassLoader now changed to '"+childClassLoader+"'");
                       System.out.println("\nNew ClassLoader chain: "+JavaEETrainingUtil.getCurrentClassloaderDetail());
                      
                       // 2. Load the caller Class within the child ClassLoader...
                       System.out.println(">> Loading '"+callerFullClassName+"' to child ClassLoader '"+childClassLoader+"'...");
                       Class<?> callerClass = childClassLoader.loadClass(callerFullClassName);
                      
                       // 3. Create a new instance of CallerClassA
                       Object callerClassInstance = callerClass.newInstance();                    
                      
               } catch (Throwable any) {
                       System.out.println("Throwable: "+any);
                       any.printStackTrace();
               }
              
               System.out.println("\nSimulator completed!");
        }
}
#### CallerClassA.java
package org.ph.javaee.training3;
import org.ph.javaee.training3.ReferencingClassA;
/**
 * CallerClassA
 * @author Rafi
 *
 */
public class CallerClassA {
       
        private final static Class<CallerClassA> CLAZZ = CallerClassA.class;
       
        static {
               System.out.println("Class loading of "+CLAZZ+" from ClassLoader '"+CLAZZ.getClassLoader()+"' in progress...");
        }
       
        public CallerClassA() {
               System.out.println("Creating a new instance of "+CallerClassA.class.getName()+"...");
              
               doSomething();
        }
       
        private void doSomething() {
              
               // Create a new instance of ReferencingClassA
               ReferencingClassA referencingClass = new ReferencingClassA();             
        }
}
#### ReferencingClassA.java
package org.ph.javaee.training3;
/**
 * ReferencingClassA
 * @author Rafi
 *
 */
public class ReferencingClassA {
       
        private final static Class<ReferencingClassA> CLAZZ = ReferencingClassA.class;
       
        static {
               System.out.println("Class loading of "+CLAZZ+" from ClassLoader '"+CLAZZ.getClassLoader()+"' in progress...");
        }
       
        public ReferencingClassA() {
               System.out.println("Creating a new instance of "+ReferencingClassA.class.getName()+"...");
        }
       
        public void doSomething() {
               //nothing to do...
        }
}
Problem reproduction
In order to replicate the problem, we will simply “voluntary” split the packaging of the application code (caller & referencing class) between the parent and child class loader.
For now, let’s run the program with the right JAR files deployment and class loader chain:
  • The main program and utility class are deployed at the parent class loader (SYSTEM classpath)
  • CallerClassA and ReferencingClassA and both deployed at the child class loader level
## Baseline (normal execution)
<JDK_HOME>\bin>java -classpath MainProgram.jar org.ph.javaee.training3.NoClassDefFoundErrorSimulator
java.lang.NoClassDefFoundError Simulator - Training 3
Author:Rafi
http://javasoulution.blogspot.in/
Current Thread name: 'main'
Initial ClassLoader chain:
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current Thread 'main' Context ClassLoader**
-----------------------------------------------------------------
>> Thread 'main' Context ClassLoader now changed to 'java.net.URLClassLoader@6a4d37e5'
New ClassLoader chain:
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9
--- delegation ---
java.net.URLClassLoader@6a4d37e5 **Current Thread 'main' Context ClassLoader**
-----------------------------------------------------------------
>> Loading 'org.ph.javaee.training3.CallerClassA' to child ClassLoader 'java.net.URLClassLoader@6a4d37e5'...
Class loading of class org.ph.javaee.training3.CallerClassA from ClassLoader 'java.net.URLClassLoader@6a4d37e5' in progress...
Creating a new instance of org.ph.javaee.training3.CallerClassA...
Class loading of class org.ph.javaee.training3.ReferencingClassA from ClassLoader 'java.net.URLClassLoader@6a4d37e5' in progress...
Creating a new instance of org.ph.javaee.training3.ReferencingClassA...
Simulator completed!

For the initial run (baseline), the main program was able to create successfully a new instance of CallerClassA from the child class loader (java.net.URLClassLoader) along with its referencing class with no problem.
Now let’s run the program with the wrong application packaging and class loader chain:
  • The main program and utility class are deployed at the parent class loader (SYSTEM classpath)
  • CallerClassA and ReferencingClassA and both deployed at the child class loader level
  • CallerClassA (caller.jar) is also deployed at the parent class loader level
## Problem reproduction run (static variable initializer failure)
<JDK_HOME>\bin>java -classpath MainProgram.jar;caller.jar org.ph.javaee.training3.NoClassDefFoundErrorSimulator
java.lang.NoClassDefFoundError Simulator - Training 3
Author:Rafi
http://javasoulution.blogspot.in/
Current Thread name: 'main'
Initial ClassLoader chain:
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current Thread 'main' Context ClassLoader**
-----------------------------------------------------------------
>> Thread 'main' Context ClassLoader now changed to 'java.net.URLClassLoader@6a4d37e5'
New ClassLoader chain:
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9
--- delegation ---
java.net.URLClassLoader@6a4d37e5 **Current Thread 'main' Context ClassLoader**
-----------------------------------------------------------------
>> Loading 'org.ph.javaee.training3.CallerClassA' to child ClassLoader 'java.net.URLClassLoader@6a4d37e5'...
Class loading of class org.ph.javaee.training3.CallerClassA from ClassLoader 'sun.misc.Launcher$AppClassLoader@214c4ac9' in progress...// Caller is loaded from the parent class loader, why???
Creating a new instance of org.ph.javaee.training3.CallerClassA...
Throwable: java.lang.NoClassDefFoundError: org/ph/javaee/training3/ReferencingClassA
java.lang.NoClassDefFoundError: org/ph/javaee/training3/ReferencingClassA
        at org.ph.javaee.training3.CallerClassA.doSomething(CallerClassA.java:27)
        at org.ph.javaee.training3.CallerClassA.<init>(CallerClassA.java:21)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at java.lang.Class.newInstance0(Unknown Source)
        at java.lang.Class.newInstance(Unknown Source)
        at org.ph.javaee.training3.NoClassDefFoundErrorSimulator.main(NoClassDefFoundErrorSimulator.java:51)
Caused by: java.lang.ClassNotFoundException: org.ph.javaee.training3.ReferencingClassA
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 9 more
Simulator completed!
What happened?
  • The main program and utility classes were loaded as expected from the parent class loader (sun.misc.Launcher$AppClassLoader)
  • The Thread context class loader was changed to child class loader as expected which includes both caller and referencing jar files
  • However, we can see that CallerClassA was actually loaded by the parent class loader (sun.misc.Launcher$AppClassLoader) instead of the child class loader
  • Since ReferencingClassA was not deployed to the parent class loader, the class cannot be found from the current class loader chain since the parent  class loader has no visibility on the child class loader, NoClassDefFoundError is thrown
The key point to understand at this point is why CallerClassA was loaded by the parent class loader. The answer is with the default class loader delegation model. Both child and parent class loaders contain the caller JAR files. However, the default delegation model is always parent first which is why it was loaded at that level. The problem is that the caller contains a class reference to ReferencingClassA which is only deployed to the child class loader; java.lang.NoClassDefFoundError condition is met.
As you can see, a packaging problem of your code or third part API can easily lead to this problem due to the default class loader delegation behaviour. It is very important that you review your class loader chain and determine if you are at risk of duplicate code or libraries across your parent and child class loaders.
Recommendations and resolution strategies
Now find below my recommendations and resolution strategies for this problem pattern:
  • Review the java.lang.NoClassDefFoundError error and identify the Java class that the JVM is complaining about
  • Review the packaging of the affected application(s), including your Java EE container and third part API’s used. The goal is to identify duplicate or wrong deployments of the affected Java class at runtime (SYSTEM class path, EAR file, Java EE container itself etc.).
  • Once identified, you will need to remove and / or move the affected library/libraries from the affected class loader (complexity of resolution will depend of the root cause).
  • Enable JVM class verbose e.g. –verbose:class. This JVM debug flag is very useful to monitor the loading of the Java classes and libraries from the Java EE container your applications. It can really help you pinpoint duplicate Java class loading across various applications and class loaders at runtime
Please feel free to post any question or comment. The next and last article of this series will focus on NoClassDefFoundError when using the “child first” delegation model.

Monday, January 27, 2014

Some of questions I came around

  1. Explain about the Request Packet flow from the browser to the DB ? Explain in detail not just high level?
  2. What are different Objects/methods inside a Servlet? JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
    JSP supports nine Implicit Objects which are listed below:
    Object Description
    requestThis is the HttpServletRequest object associated with the request.
    responseThis is the HttpServletResponse object associated with the response to the client.
    outThis is the PrintWriter object used to send output to the client.
    sessionThis is the HttpSession object associated with the request.
    applicationThis is the ServletContext object associated with application context.
    configThis is the ServletConfig object associated with the page.
    pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
    pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
    ExceptionThe Exception object allows the exception data to be accessed by designated JSP.

    The request Object:

    The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
    The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
    We would see complete set of methods associated with request object in coming chapter: JSP - Client Request.

    The response Object:

    The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client.
    The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
    We would see complete set of methods associated with response object in coming chapter: JSP - Server Response.

    The out Object:

    The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
    The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered='false' attribute of the page directive.
    The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
    Following are the important methods which we would use to write boolean char, int, double, object, String etc.
    Method Description
    out.print(dataType dt)Print a data type value
    out.println(dataType dt)Print a data type value then terminate the line with new line character.
    out.flush()Flush the stream.

    The session Object:

    The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.
    The session object is used to track client session between client requests. We would see complete usage of session object in coming chapter: JSP - Session Tracking.

    The application Object:

    The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
    This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
    By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it.
    You can check a simple use of Application Object in chapter: JSP - Hits Counter

    The config Object:

    The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
    This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
    The following config method is the only one you might ever use, and its usage is trivial:
     
    config.getServletName();
    This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INF\web.xml file

    The pageContext Object:

    The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
    This object is intended as a means to access information about the page while avoiding most of the implementation details.
    This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
    The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
    The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.
    One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope:
     
    pageContext.removeAttribute("attrName", PAGE_SCOPE);
    You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.

    The page Object:

    This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
    The page object is really a direct synonym for the this object.

    The exception Object:

    The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.
     
  3. What are the different Marker interfaces and Does the Serializable contains the methods how you will persist an object ?
  4. What is complete Memory Layout on java ?
  5. If you are given parking plot and Ask you to design a software, how will you do that ? How you will gather requirements from the owner?
  6. Does the Web server contains the web.xml  and how it does the Load balancing (J2EE Servers and Application servers)
  7. What is XSS/CSRF ? Explain in detailed ?
  8. Differences of JSPs and Servlets ?
  9. JSP is a Java view technology running on the server machine which allows you to write template text in (the client side languages like HTML, CSS, JavaScript and so on). JSP supports the so-called taglibs which are backed by pieces of Java code with which you can control the page flow and/or output dynamically (programmatically). A well known taglib is JSTL. JSP also supports Expression Language which can be used to access backend data (actually, the attributes which are available in page, request, session and application scopes), mostly in combination with taglibs. When a JSP is requested for the first time or when the webapp starts up, the servlet container will compile it into a class extending HttpServlet and use it during the webapp's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the /work directory. On a JSP request, the servletcontainer will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the webserver over network to the client side which in turn displays it in the webbrowser.

    Servlets

    Servlet is an Java application programming interface (API) running on the server machine which can intercept on the requests made by the client and can generate/send a response accordingly. A well known example is the HttpServlet which provides methods to hook on HTTP requests using the popular HTTP methods such as GET and POST. You can configure HttpServlets to listen on a certain HTTP URL pattern, which is configureable in web.xml, or more recently with Java EE 6, with @WebServlet annotation.
    When a Servlet is requested for the first time or when the webapp starts up, the servlet container will create an instance of it and keep it in memory during webapp's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by HttpServletRequest and handle the response by HttpServletResponse. Both objects are available as method arguments inside any of the overridden methods of HttpServlet, such as doGet() and doPost().

    JSF (JavaServer Faces)

    JSF is a component based MVC framework which is built on top of the Servlet API and provides components in flavor of taglibs which can be used in JSP or any other Java based view technology such as Facelets. Facelets is mucha more suited to JSF than JSP. It namely provides great templating capabilities such as composite components, while JSP basically only offers the <jsp:include> for templating, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work in JSF) when you want to replace a repeated group of components by a single component. If you can, I recommend to drop JSP and go for Facelets when you want to develop with JSF.
    As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a Javabean class as Model. The JSF components are been used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet uses the JSF component tree to do all the work.

    Related questions

  10. What is the main-stream Java alternative to ASP.NET / PHP?
  11. Java EE web development, what skills do I need?
  12. How do servlets work? Instantiation, session variables and multithreading
  13. What is a Javabean and where are they used?
  14. How to avoid Java code in JSP files?



 

ServletContext

When the servletcontainer (like Apache Tomcat) starts up, it will deploy and load all webapplications. When a webapplication get loaded, the servletcontainer will create the ServletContext once and keep in server's memory. The webapp's web.xml will be parsed and every Servlet, Filter and Listener found in web.xml will be created once and kept in server's memory as well. When the servletcontainer shuts down, it will unload all webapplications and the ServletContext and all Servlet, Filter and Listener instances will be trashed.

HttpServletRequest and HttpServletResponse

The servletcontainer is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a webbrowser) sends a HTTP request, the servletcontainer will create new HttpServletRequest and HttpServletResponse objects and pass it through the methods of the already-created Filter and Servlet instances whose url-pattern matches the request URL, all in the same thread.
The request object provides access to all information of the HTTP request, such as the request headers and the request body. The response object provides facility to control and send the HTTP response the way you want, such as setting headers and the body (usually with HTML content from a JSP file). When the HTTP response is committed and finished, then both the request and response objects will be trashed.

HttpSession

When a client visits the webapp for the first time and/or the HttpSession is to be obtained for the first time by request.getSession(), then the servletcontainer will create it, generate a long and unique ID (which you can get by session.getId()) and store it in server's memory. The servletcontainer will also set a Cookie in the HTTP response with JSESSIONID as cookie name and the unique session ID as cookie value.
As per the HTTP cookie specification (a contract a decent webbrowser and webserver has to adhere), the client (the webbrowser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. Using a HTTP header checker tool like Firebug you can check them. The servletcontainer will determine every incoming HTTP request header for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.
The HttpSession lives until it has not been used for more than the <session-timeout> time, a setting you can specify in web.xml, which defaults to 30 minutes. So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one.
On the other hand, the session cookie on the client side has a default lifetime which is as long as the browser instance is running. So when the client closes the browser instance (all tabs/windows), then the session will be trashed at the client side. In a new browser instance the cookie associated with the session won't be sent anymore. A new request.getSession() would return a brand new HttpSession and set a cookie with a brand new session ID.

In a nutshell

  • The ServletContext lives as long as the webapp lives. It's been shared among all requests in all sessions.
  • The HttpSession lives as long as the client is interacting with the webapp with the same browser instance and the session hasn't timed out at the server side yet. It's been shared among all requests in the same session.
  • The HttpServletRequest and HttpServletResponse lives as long as the client has sent it until the complete response (the webpage) is arrived. It is not being shared elsewhere.
  • Any Servlet, Filter and Listener lives as long as the webapp lives. They are being shared among all requests in all sessions.
  • Any attribute which you set in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives.

Threadsafety

That said, your major concern is possibly threadsafety. You should now have learnt that Servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise have been too expensive to recreate it on every request.
But you should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's threadunsafe! The below example illustrates that:
public class MyServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } }



A: JavaServer Faces technology is a framework for building user interfaces for web applications. JavaServer Faces technology includes:
A set of APIs for: representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.
A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.
JSP is a specialized kind of servlet.
JSF is a set of tags you can use with JSP.