Wednesday, June 30, 2010

Winner Announcement!

The winner for the Month of June is Sekhar Chandraju!

Monday, June 7, 2010

What, Why and How java.lang.OutOfMemoryError:



                                                                                                                   -Sekhar Chandraju


The java.lang.OutOfMemoryError  is the subclass of java.lang.VirtualMachineError which is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made  available by the garbage collector.

When we encounter a java.lang.OutOfMemoryError,  it is not always the best idea to analyze Java heap dumps. We first need to investigate the root cause of the java.lang. OutOfMemoryError. Only after the root cause is identified we can decide whether or not to analyze Java heap dumps.

Obviously, memory is the exhausted resource for a java.lang.OutOfMemoryError. Unfortunately, the Java specification of java.lang.OutOfMemoryError does not elaborate further on what kind of memory it's talking about

There are six different types of runtime data areas, or memory areas, in the Java Virtual Machine.



















Program Counter Register:

The Program Counter Register, also known as the pc register, stores the address of the Java byte code instruction that is currently being executed (just like the processor register in our central processing). java.lang.OutOfMemoryError is not thrown from the pc register since a program counter is not conventionally considered as a memory.

Java Virtual Machine Stack:

Java Virtual Machine Stacks contain frames where data, return values, and partial execution results are stored. These can be expanded during runtime. If there's not enough memory for the expansion of an existing Java Virtual Machine stack, or for the creation of a new Java Virtual Machine stack for a new thread, the Java Virtual Machine will throw a java.lang.OutOfMemoryError.

Heap:

The Heap is where instances of Java classes and arrays are allocated. A java.lang.OutOfMemoryError will be thrown when there is not enough memory available for instances of Java classes or arrays.


Native Method Stack:

Native Method Stacks store conventional stacks, also known as C stacks, to support native methods that are written in a non-Java language such as C/C++. Native memory stacks can be expanded during runtime. If there's not enough memory for the expansion of an existing native memory stack or for the creation of a new native memory stack for a new thread, you would see a java.lang.OutOfMemoryError.

Method Area:

The Method Area stores class-related information, the runtime constant pool, for instances, the code for methods and constructors, and field/method data. If there's not enough memory in the method area, you will encounter java.lang.OutOfMemoryError.

Runtime Constant Pool:

The Runtime Constant Pool contains constants such as field references and literals. A java.lang.OutOfMemoryError will be thrown when not enough memory is available for the construction of the runtime constant pool area

       
Types of Error messages:

Now we have understood which memory areas throw java.lang.OutOfMemoryError. We will see types of  OutOfMemoryError and their root causes

java.lang.OutOfMemoryError: Requested array size exceeds VM limit  -- This error message indicates that there is a memory request for an array but that's too large for a predefined limit of a virtual machine. We need to check the source code to make sure that there's no huge array created dynamically or statically. Fortunately, latest virtual machines usually do not have this limit.

java.lang.OutOfMemoryError: PermGen space --  We  will see an OutOfMemoryError when the Permanent Generation area of the Java heap is full, like the above message. we can just use the -XX:MaxPermSize command-line option to increase the maximum limit of the permanent generation. For example, -XX:MaxPermSize=128m will set the maximum size of the permanent generation to 128 Mbytes

java.lang.OutOfMemoryError: requested NNN bytes for MMMM. Out of swap space?
Literally you could check the operating system configuration for swap space. It seems that the Java Virtual Machine is not sure if the swap space is the root cause of the problem (?).We can check whether this Java Virtual Machine is consuming too much native memory .We also need to make sure there's enough memory for this JVM and no other processes are consuming most of memory resource. The last thing we can try is to find any known defects related to the module, MMMM.
java.lang.OutOfMemoryError: unable to create new native thread -- This kind of message is seen when you have an excessive number of threads or if the native memory is exhausted and a thread is attempting to be created.

Exception in thread "main" java.lang.OutOfMemoryError
at sun.misc.Unsafe.allocateMemory (Native Method)
In this message there's no clue whether it's native memory or a Java heap. But “sun.misc.Unsafe.allocateMemory (Native Method)"  indicates that it might be native memory related.

java.lang.OutOfMemoryError: JVMCI046: allocateMemory failed -- In the following case, the Java virtual machine is kind enough to tell us that there's native memory exhaustion. In the message, the Java virtual machine says "allocateMemory failed" which means a native memory allocation failed:

If you find that heap space is the root cause for OutOfMemoryError, then we can dive into heap analysis. Before doing that we have to get the Java Heap Dump.

Java Heap Dump:

A Java heap dump is a snapshot of a Java heap at a specific time. A Java heap dump is usually automatically generated by the Java Virtual Machine, but you can also force Java heap dump generation. You can find Java heap dumps in the current working directory of the Java Virtual Machine process.  Heap analyzers have to be used to read Java heap dumps.

Heap Analyzer:

Heap analyzer tools like IBM Heap Analyzer, HAT, jhat, alphaWorks etc., are used to analyze the heap dump. The first thing to analyze is memory leak. Memory leaks can be because of a static variable, local variable or local thread.

Memory leak patterns:

·         Horizontal memory leak: Many objects are referenced from same objects. The following picture shows the simulation of horizontal memory leak using Heap analyzer.

 
·         Vertical memory leak: Many objects are linked together. The following picture shows the simulation of vertical memory leak using Heap analyzer.



 
·      



·         Diagonal memory leak: Combination of horizontal and vertical memory leak. It's often found in tree structures. The following picture shows the simulation of diagonal memory leak using Heap analyzer.







Conclusion:
      We've investigated different patterns of java.lang.OutOfMemoryError, artifacts and their possible solutions. When we see a java.lang.OutOfMemoryError and find Java heap dumps; however, it's not always necessary to analyze Java heap dumps. We often find many people blindly jumping on Java heap dumps without looking into other information. We can't diagnose all kinds of problems by analyzing the Java heap dumps alone. Java heap dumps are just snapshots of Java heap at specific times. Garbage collection trace is another source of information where we can figure out what's going on with the Java heap and garbage collector.

      First, we need to determine whether java.lang.OutOfMemoryError is caused by Java heap, native memory or something else from error messages. If it's caused by native memory, we need to utilize operating system memory monitoring tools provided by an operating system such as svmon on AIX operating systems or your favourite third-party tools. If java.lang.OutOfMemoryError is related to Java heap, we need to make sure that the Java heap and parts of the Java heap are configured well enough to handle a given workload by analyzing garbage collection trace. If your JVM needs a little bit more Java heap and you have extra memory, you could endow more memory to the Java Virtual Machine in order to increase heap capacity, for example, by increasing the -Xmx command-line option. If you've already reached the address space limit, you could redistribute the workload with multiple horizontal clones of the Java Virtual Machine. If you really suspect there's Java heap leak, you are more than welcome to analyze the Java heap dumps with any of your favourite Java heap analysis tools.



Sunday, June 6, 2010

Java Server Faces

                                                                                                                                      - Adam Shaik

Evolution of MVC Architecture


1. No MVC
2. MVC Model 1 (Page-centric)
3. MVC Model 2 (Servlet-centric)
4. Web application frameworks, Struts
5. Standard-based Web application framework?
    Java Server Faces (JSR-127)


Now when we talk about Web application framework, we are basically talking about the evolution of MVC architecture, which stands for Model, View, and Controller.


So in the beginning, we used no MVC.  Then we had JSP Model1 and Model 2 architecture.  And people came up with so called Web application frameworks such as Apache Strut based on Model 2 architecture.  And finally we are at the phase there will be a standard based Web application framework.

What is & Why JSF?

In short, JSF is a server side user interface component framework for Java technology based Web applications.

Please note that it is server side instead of client side framework. What this means is that, in JSF architecture, many things that are related to UI management are handled at the server instead of at client side.  Of course, the prime example of client side UI framework is Swing.

Please also note that JSF is a UI component framework.  What this means is, under JSF architecture, UI is handled by a set of UI components as we will learn later on.  The concept of UI component is very important in understanding JSF.

What is JSF?

In a bit more technical definition, JSF is a specification and reference  implementation for Web application development framework.  And the specification defines various things such as UI component model, event and listener model, validator model, back-end data integration model.


The goal of JSF is to allow tool vendors to provide easy to use tools leveraging JSF underneath so that developers can build Web applications using, for example, drag and drop model as they do in standalone Swing based applications.  And a good example of the tool that leverages JSF underneath is Sun Java Studio Creator.





Why JSF?

Now let's talk about value propositions of JSF.  You can consider JSF provides the MVC based Web application framework.  Again it provides clean separation of roles as we
will talk about later in this presentation.  JSF is easy to use.  And it provides UI component framework which is extensible.  It also provides rendering architecture in which UI components can be associated with multiple renderers. JSF is also designed with multiple client types in mind.

One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation. Web applications built with JSP technology partially achieve this separation. However, a JSP application cannot map HTTP requests to component-specific event handling or manage UI elements as stateful objects on the server. JavaServer Faces technology allows you to build Web applications that implement finer- grained separation of behavior and presentation traditionally offered by client-side UI architectures.

The separation of logic from presentation also allows each member of a Web application development team to focus on their piece of the development process, and provides a simple programming model to link the pieces together. For example, Page Authors with no programming expertise can use UI component tags to link to application code from within a Web page without writing any scripts.


Another important goal of Java Server Faces technology is to leverage familiar UI- component and Web-tier concepts without limiting you to a particular scripting technology or markup language. While Java Server Faces technology includes a JSP custom tag library for representing components on a JSP page, the Java Server Faces technology APIs are layered directly on top of the Servlet API. This layering of APIs enables several important application use-cases such as: using another presentation technology besides JSP pages, creating your own custom components directly from the component classes, and generating output for different client devices.


Most importantly, Java Server Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
·        JSP and Servlet
        No built-in UI component model
·        A few words on Struts first
        I am not saying you should not use Struts
        Struts and JSF can be used together
·        Struts
        No built-in UI component model
        No built-in event model for UI components
        No built-in state management for UI components
        No built-in support of multiple renderers (Struts is more or less tied up with HTML)


So in summary, why do we need JSF when we have Servlet and JSP?  Furthermore, why do we need JSF when we have a popular web application frameworks such as Struts?


As was mentioned, JSP and Servlet do not provide built-in UI Component model.


What about Struts?  Struts is designed with a different focus.  The focus of Struts is to provide a controller framework while the focus of JSF is to provide UI component framework.  So Struts does not provide the built-in UI component model.  And because of that, it does not support UI component event model, nor state management of UI components, and because Struts is more or less tied up with HTML, it does not support the independence between UI components and a particular renderer.
JSF Design Goals

·            Tool friendly
·            Client device / protocol neutral
·           Usable with Java Server Pages (JSP)
·           Usable without JSP
·            Useful in the context of HTML and today's browsers
·            Scalable


When JSF expert group started working on JSF specification, they had a few things in mind.


First, JSF should be tool friendly.  If you think about how developers are building Swing application, they don't  write their apps directly using Swing APIs. Instead, they would use an IDE in which they can do drag and dropping UI widgets. And the JSF expert group expect the same thing for building Web applications. They expect tool vendors will provide a way in which developers can drag and drop UI widgets for building Web applications.


The next goal is to make JSF to be client device and protocol neutral.  That is, there has to be a clean separation between UI component model and how UI components are rendered to a particular client using a particular protocol.  Of course, HTML browser using HTTP protocol is the most pervasive form of client device and protocol and they should be well supported.  But the point is the UI component model should be able to accommodate other client types and protocols easily as they come.

JSF 1.x uses JavaServer Pages (JSP) for its display technology, but can also accommodate other technologies (such as XUL and Facelets). JSF 2 uses Facelets by default for this purpose. Facelets is a more efficient, simple, and yet more powerful view description language (VDL).




Quick Overview on JSF Architecture, Concept & Features


As I mentioned, JSF provides User interface framework, which runs on the service side.

Let's say a client makes a request.  The request goes across the network to the server, where JSF framework builds up UI representation and renders back to the client in whatever mark up language that is appropriate to the client.

The user interacts with that page, and submit a request to the server for processing. The JSF framework then interprets the request parameters, and decode them and converts them into events and dispatch them to event handling logic.
 

 
This picture shows JSF architecture in a somewhat simplified manner.

Just like any other MVC-based architecture, JSF architecture has its own Front controller called FacesServlet. The role of this controller is basically a gatekeeper.


As we will learn later on, a JSF page is made of a tree of UI components. These UI components can be associated with backend model objects called backing beans.  These backing beans handle application logic (or sometimes called business logic) handling.


When a page has to be rendered to a particular client type, whether the client type  is a HTML browser running on a desktop or WML browser running on a wireless phone, a particular renderer is used for displaying the data maintained in the UI components. In other words, a same UI component is used for displaying information on different client types using different protocols.



Important Basic Capabilities


·           Extensible UI component model
·           Flexible rendering model
·           Event handling model
·           Validation framework
·           Basic page navigation support
·           Internationalization
·           Accessibility


So just to repeat the important JSF features and capabilities here one more time, JSF UI component model is extensible.  That is, you as a developer can use the built-in UI components that come with a typical JSF implementation or you can extend them.  JSF also provides flexible rendering model as was mentioned.  That is, UI components in JSF are not tied with a particular rendering technology such as HTML. This means any rendering technology can be used for displaying information maintained in the UI components.

JSF also supports event handling model.  For example, when you click on a UI component on a JSF page, it will generate an event and any server side programs which registered to receive event notifications will be notified.

JSF also supports page navigation through a configuration file. In this sense, this is quite similar with Struts.


JSF also supports internationalization and accessibility.




Key JSF Concepts

UIComponent
 Render-independent characteristics,  Base class with standard behaviors
Standard UIComponent Subclasses:
UICommand, UIForm, UIGraphic, UIInput, UIOutput, UIPanel, UISelectBoolean, UISelectMany, UISelectOne
FacesEvent
 Base class for request and application events
Validator
 Base class for standard and application defined validators         
So let's go over some of the key JSF concepts.  Again, we talked about these concepts already a bit.

First, the concept of UI component is extremely important for you to understand. I would say that if you understand the concept of UI component, you understand
90% of JSF architecture.

Converter
 Plug-in for String-Object conversion
 FacesContext
-     Servlet request, response, session, JSF request, response trees
-   Model reference expression evaluators,Syntax similar to the expression language of the JSP Standard Tag Library (JSTL) 1.x ,Primary interface between components and the data provided by (or to) the application

Renderer
–   Converts components to and from a specific markup language
–   Supports render-dependent attributes on components
–   May support more than one component type
RenderKit
–   Library of Renderers
–   Extensible at runtime
–   Basic HTML RenderKit is part of the specification

























Because of the division of labor enabled by the JavaServer Faces technology design, JavaServer Faces application development and maintenance can proceed quickly and easily.


The members of a typical development team are those mentioned in the picture above. In many teams, individual developers play more than one of these roles, however, it is still useful to consider JavaServer Faces technology from a variety of perspectives based on primary responsibility.

JSF specification implementations

·        IceSoft’s Ice Faces

·        Apache’s MyFaces

·        Oracle’s ADF Faces

·        JBoss RichFaces.


In next article, we will go through more on developing the application, deploying the application.