Tuesday, March 18, 2008

Create graphics applications with Java 3D

Since version 1.2, Java 3D is developed under the Java Community Process. Java 3D runs on top of OpenGL or Direct3D; it's also an interface that encapsulates graphics programming using a real, object-oriented concept. In addition, Java 3D offers extensive 3D sound support.

This article describes a scene that is constructed using a scene graph, which is a representation of the objects that have to be shown. This scene graph is structured as a tree containing several elements that are necessary to display the objects.


Ref: View Complete

Wednesday, September 19, 2007

Struts Overview

What is Struts?

Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open source. Struts Framework is suited for the application of any size. Latest version of struts can be downloaded from http://jakarta.apache.org/. We are using jakarta-struts-1.1 and jakarta-tomcat-5.0.4 for this tutorial.

What is Model-View-Controller (MVC) Architecture?

Model-View-Controller architecture is all about dividing application components into three different categories Model, View and the Controller. Components of the MVC architecture has unique responsibility and each component is independent of the other component. Changes in one component will have no or less impact on other component. Responsibilities of the components are:

Model: Model is responsible for providing the data from the database and saving the data into the data store. All the business logic are implemented in the Model. Data entered by the user through View are check in the model before saving into the database. Data access, Data validation and the data saving logic are part of Model.

View: View represents the user view of the application and is responsible for taking the input from the user, dispatching the request to the controller and then receiving response from the controller and displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of view component.

Controller: Controller is intermediary between Model and View. Controller is responsible for receiving the request from client. Once request is received from client it executes the appropriate business logic from the Model and then produce the output to the user using the View component. ActionServlet, Action, ActionForm and struts-config.xml are the part of Controller.

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

1. They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
2. They are expressive: By using the MVC design pattern our application becomes more expressive.

1). Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.

2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.

3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.

Difference between Model 1 and Model 2 architecture:

Features of MVC1:

1. Html or jsp files are used to code the presentation. To retrieve the data JavaBean can be used.
2. In mvc1 archictecture all the view, control elements are implemented using Servlets or Jsp.
3. In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call.

Features of MVC2:

1. The MVC2 architecture removes the page centric property of MVC1 architecture by separating Presentation, control logic and the application state.
2. In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.


Struts is an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture. Struts framework provides three key components:

1. A request handler provided by the application developer that is used to mapped to a particular URI.
2. A response handler which is used to transfer the control to another resource which will be responsible for completing the response.
3. A tag library which helps developers to create the interactive form based applications with server pages.

Struts provides you the basic infrastructure infrastructure for implementing MVC allowing the developers to concentrate on the business logic.

Overview of the Struts Framework

The Struts framework is composed of approximately 300 classes and interfaces which are organized in about 12 top level packages. Along with the utility and helper classes framework also provides the classes and interfaces for working with controller and presentation by the help of the custom tag libraries. It is entirely on to us which model we want to choose. The view of the Struts architecture is given below:

The Struts Controller Components:

Whenever a user request for something, then the request is handled by the Struts Action Servlet. When the ActionServlet receives the request, it intercepts the URL and based on the Struts Configuration files, it gives the handling of the request to the Action class. Action class is a part of the controller and is responsible for communicating with the model layer.

The Struts View Components:

The view components are responsible for presenting information to the users and accepting the input from them. They are responsible for displaying the information provided by the model components. Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the capability of the view we can use the Custom tags, java script etc.

The Struts model component:

The model components provides a model of the business logic behind a Struts program. It provides interfaces to databases or back- ends systems. Model components are generally a java class. There is not any such defined format for a Model component, so it is possible for us to reuse Java code which are written for other projects. We should choose the model according to our client requirement.

Thursday, September 13, 2007

NavigableSet and ConcurrentSkipListSet

Suppose we have a requirement, from sorted set elements [5,10,15,20] we want few things like this
  • Retrieve the element which is immediately greater than or lower than element 15
  • Retrieve all elements greater than or lower than 10
With the help of existing methods we need to take few risks to achieve them. But with NavigableSet methods it becomes just a method call.NavigableSet methods used to return the closest matches of elements for the given elements in the collection. ConcurrentSkipListSet is one of the class that implements NavigableSet.

Example

import java.util.concurrent.*;
import java.util.*;
class SkipListSetTest
{
public static void main(String[] args)
{
ConcurrentSkipListSet csls = new ConcurrentSkipListSet();
csls.add(15);
csls.add(20);
csls.add(5);
csls.add(10);
System.out.println("Elements in the collections are");
for(Integer i: csls)
{
System.out.println(i);
}
/* Retrieve immediate element less than or equal to the given element */
System.out.println("Floor "+csls.floor(12));
/* Retrieve immediate element greater than or equal to the given element */
System.out.println("Ceiling "+csls.ceiling(12));
/* Retrieve immediate element less than the given element */
System.out.println("Lower "+csls.lower(10));
/* Retrieve immediate element greater than the given element */
System.out.println("heigher "+csls.higher(10));
System.out.println("Head Elements ");
Set cslsHeadView = csls.headSet(10);
//HeadSet excludes the given element
for(Integer i: cslsHeadView)
{
System.out.println(i);
}
Set cslsTailView = csls.tailSet(10);
//TailSet includes the given element
System.out.println("Tail Elements");
for(Integer i: cslsTailView)
{
System.out.println(i);
}
}
}

Output:

Elements in the collections are
5
10
15
20
Floor 10
Ceiling 15
Lower 5
heigher 15
Head Elements
5
Tail Elements
10
15
20

NavigableMap and ConcurrentSkipListMap

NaviagableMap is similar to NaviagableSet. In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements NaviagableMap.

import java.util.*;
import java.util.concurrent.*;

class NavigableMapExample
{
public static void main(String[] args)
{
NavigableMap nm = new ConcurrentSkipListMap();
nm.put(1,"One");
nm.put(2,"Two");
nm.put(3,"Three");
nm.put(4,"Four");
nm.put(5,"Five");
/* Retrieves the key,value pair immediately lesser than the given key */
Map.Entry ae = nm.lowerEntry(5);
/* Map.Entry is a Static interface nested inside Map
interface,just use to hold key and value */
System.out.println("Key" + ae.getKey());
System.out.println("Value"+ ae.getValue());
/* Retrieves key,value pairs equal to and greater then the given key */
SortedMap mm = nm.tailMap(3);
Set s = mm.keySet();
System.out.println("Tail elements are");
for(Integer i:s)
{
System.out.println("Key "+ i + "Value "+ mm.get(i));
}
}
}

output

Key 4
Value Four
Tail elements are
Key 3 Value Three
Key 4 Value Four
Key 5 Value Five

Notes :
floorEntry method retrieves less than or equal to the givenkey (or) null
lowerEntry method retrieves always less than the givenkey (or) null
headMap method retrieves all elements less than the givenkey
tailMap method retrieves all elements greater than or equal to the givenkey

AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry

AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry are a static classes nested inside abstractMap class.The instance of this classes use to hold the key,value pair of one single entry in a Map.The difference between these two classes is that former one allow us to set the value and later one if we try to set the value, it throws UnsupportedOperationException
Modified classes

Classes are modified to implement the new interfaces in the existing classes.LinkedList is modified to implement Deque. TreeSet is modified to implement NavigableSet.TreeMap is modified to implement NavigableMap.In Collections 2 new methods newSetFromMap and asLifoQueue are added.

Wednesday, September 12, 2007

Synchronization in Java

Why Synchronization

The biggest problem of allowing multiple threads sharing the same data set is that one operation in one thread could collide with another operation in another threads on the same data. When this happens, the result is un-desirable.

Let's use a bank application program as an example.
Assuming that the program has multiple threads running, with each thread connecting an ATM system, and you have a saving account in the bank with $100.00, now you and your friend are going to two different ATMs at about the same time, and trying to withdraw $50.00 from your account, what do you think it will happen?

If the threads are running independently, the following could happen:

Time 01:01 02:01 03:01 04:01
+----------+---------+---------+-------
Thread 1 Get Set
Action You Account Account You
Withdraw Balance Balance Receive
$50.00 $100.00 $50.00 $50.00

Time 01:02 02:02 03:02 04:02
-+----------+---------+---------+------
Thread 2 Get Set
Action Friend Account Account Friend
Withdraw Balance Balance Receive
$50.00 $100.00 $50.00 $50.00

Time 01:01 02:01 03:01 04:01
-----------++--------++--------++------
Account $100.00 $100.00 $50.00 $50.00

Both you and your friend will receive $50.00 each, and your account will still have $50.00. The bank could lose $50.00.

The solution this problem is synchronization.

What Is Synchronization

Synchronization is a programming technique that involves 3 elements:

* Lock: An object with two states: locked and unlocked.
* Synchronized Block: A block of statements that is associated with a lock.
* Synchronization Rule: When a synchronized block is encountered in a thread of execution, the associated lock will be checked. If the lock locked, the execution will be stopped until the lock is unlocked. If the lock is unlocked, the lock will be locked, and the synchronized block of statements will be executed. When the execution reaches the end of the synchronized block, the lock will be unlocked. With this rule, two synchronized blocks associated with same lock will never be executed at the same time.

Now let's see if we can use the synchronization technique in the bank application program to help the bank. Let's define a synchronization block starting from the "Get Account Balance" action to the "Set Account Balance" action in each thread, and associate the block with a lock. With this change, both you and your friend can still withdraw $50.00, but your account will have nothing left:

Time 01:01 02:01 03:01 04:02
-----------+---------++--------++-------
Lock Unlocked Locked Locked Unlocked

Time 01:01 02:01 03:01 04:01
+----------+---------+---------+--------
Thread 1 Get Set
Action You Account Account You
Withdraw Balance Balance Receive
$50.00 $100.00 $50.00 $50.00

Time 01:02 02:02 03:02 04:02 05:02
-+----------+---------+---------+---------+------
Thread 2 Get Get Set
Action Friend Account Account Account Friend
Withdraw Balance Balance Balance Receive
$50.00 Stopped $50.00 $0.00 $50.00

Time 01:01 02:01 03:01 04:02 05:02
-----------++--------++--------++---------+------
Account $100.00 $100.00 $50.00 $0.00 $0.00

The synchronization technique did help the bank from losing money. But it also increased the total transaction time.


Synchronization Support in Java

Instead of let the programmers to design their own locks, manage the synchronization blocks, and apply the synchronization rules, Java offers a synchronization monitor on each instance of the Object class, so it can be used as a synchronization lock. Since all classes are sub classes of Object, all objects in Java can be used as synchronization locks.

Java also offers three ways to define synchronized blocks.

Synchronized Class Method:

class class_name {
static synchronized type method_name() {
statement block
}
}

All the statements in the method become the synchronized block, and the class object is the lock.

Synchronized Instance Method:

class class_name {
synchronized type method_name() {
statement block
}
}

All the statements in the method become the synchronized block, and the instance object is the lock.

Synchronized Statement:

class class_name {
type method_name() {
synchronized (object) {
statement block
}
}
}

All the statements specified in the parentheses of the synchronized statement become the synchronized block, and the object specified in the statement is the lock.

Java applys the synchronization rule by assigning the ownership of the lock's monitor to the threads that are running the synchronized blocks. Here is how it works:

* When a synchronized clock is reached in an execution thread, it will try to gain the ownership of the monitor of the lock object. If another thread owns the lock's monitor, it will wait.
* Once the lock's monitor is free, the waiting thread will become the owner of the lock's monitor, and start to execute the synchronized block.
* Once the synchronized block is executed to the end, the lock's monitor will be freed again.

Note that one program can have many locks and each lock can be associated with many different synchronized blocks. But the synchronization rule only applies between the synchronized block and its associated lock.

For example, the following code defines two synchronized blocks. Both are associated with the same lock, the instance object.

class class_name {
type method_name() {
synchronized (this) {
statement block 1
}
}
synchronized type method_name() {
statement block 2
}
}

Block 1 will never be executed at the same time as block 2.

The following code defines two synchronized blocks. But they are associated with two different locks, one is the class object, and the other is the instance object. Those two synchronized blocks will never wait for each other.

class class_name {
type method_name() {
synchronized (this) {
statement block 1
}
}
static synchronized type method_name() {
statement block 2
}
}

Thursday, September 6, 2007

Java 6.0 New Collection APIs

Java 6.0 New Collection APIs

The following are the new collection APIs introduced in Java 6.0. I listes them as Interfaces and classes.

New Interfaces
  • Deque
  • BlockingDeque
  • NavigableSet
  • NavigableMap
New Classes
  • ArrayDeque
  • LinkedBlockingDeque
  • ConcurrentSkipListSet
  • ConcurrentSkipListMap
  • AbstractMap.SimpleEntry
  • AbstractMap.SimpleImmutableEntry
Updated Classes in Java 6.0
  • LinkedList
  • TreeSet
  • TreeMap
  • Collections
Deque and ArrayDeque
Deque is the abbreviation of “Double Ended Queue”. A Collection that allows us to add (or) remove elements at both ends. Deque supports total size of collection for both fixed and unspecified size limits.
Deque implementation can be used as Stack(Last in first out ) or Queue(First in First Out). For each insertion, retrieval and removal of elements from deque there exists methods in 2 flavours. One will throw exception if it fails in an operation and another one returns status or special value for each operation.
Operation Special value method Exception throwing method

Operation Special value method Exception throwing method

Insertion at head offerFirst(e) addFirst(e)
Removal at head pollFirst() removeFirst()
Retrieval at Head peekFirst() getFirst()
Insertion at Tail offerLast(e) addLast(e)
Removal at Tail pollLast() removeLast()
Retrieval at Tail peekLast() getLast()
Implementation of Deque doesn’t require preventing the insertion of null, but when we are using special value method null is return to indicate that collection is empty. So it is recommendable not to allow insertion of null.

ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stack and faster than linked list when used as queue. ArrayDeque is not thread Safe. The following example explains how to write program using ArrayDeque.

Example

import java.util.ArrayDeque;
import java.util.Iterator;

public class DequeExample
{
public static void main(String as[])
{
ArrayDeque adObj = new ArrayDeque();
//Insertion by using various methods

adObj.add("Oracle");
adObj.addFirst("DB2");
adObj.offerFirst("MySQL"); //returns boolean - true R false
adObj.offerLast("Postgres"); //returns boolean - true R false

//Retrievals

System.out.println("Retrieving First Element :" + adObj.peekFirst());
System.out.println("Retrieving Last Element :"+ adObj.peekLast());

//Removals

System.out.println("Removing First Element :"+ adObj.pollFirst());
System.out.println("Removing Last Element :"+ adObj.pollLast());

//Reverse traversal

System.out.println("Remaining Elements :");
Iterator it = adObj.descendingIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}

Output:

Retrieving First Element :MySQL
Retrieving Last Element :Postgres
Removing First Element :MySQL
Removing Last Element :Postgres
Remaining Elements :
Oracle
DB2

BlockingDeque and LinkedBlockingDeque

A BlockingDeque is similar to Deque and provides additionally functionality. When we tries to insert an element in a BlockingDeque, which is already full, it can wait till the space becomes available to insert an element. We can also specify the time limit for waiting.

Saturday, September 1, 2007

Implicit Objects

Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects are Java objects that the JSP Container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.

There are many implicit objects available. Some of them are:

request: The class or the interface name of the object request is http.httpservletrequest. The object request is of type Javax.servlet.http.httpservletrequest. This denotes the data included with the HTTP Request. The client first makes a request that is then passed to the server. The requested object is used to take the value from client’s web browser and pass it to the server. This is performed using HTTP request like headers, cookies and arguments.

response: This denotes the HTTP Response data. The result or the information from a request is denoted by this object. This is in contrast to the request object. The class or the interface name of the object response is http.HttpServletResponse. The object response is of type Javax.servlet.http. >httpservletresponse. Generally, the object response is used with cookies. The response object is also used with HTTP Headers.

Session: This denotes the data associated with a specific session of user. The class or the interface name of the object Session is http.HttpSession. The object Session is of type Javax.servlet.http.httpsession. The previous two objects, request and response, are used to pass information from web browser to server and from server to web browser respectively. The Session Object provides the connection or association between the client and the server. The main use of Session Objects is for maintaining states when there are multiple page requests. This will be explained in further detail in following sections.

Out: This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter

PageContext: This is used to access page attributes and also to access all the namespaces associated with a JSP page. The class or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext

Application: This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext. The Application object is written: Javax.servlet.http.ServletContext

Config: This is used to get information regarding the Servlet configuration, stored in the Config object. The class or the interface name of the Config object is ServletConfig. The object Config is written Javax.servlet.http.ServletConfig

Page: The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object

The most commonly used implicit objects are request, response and session objects

Servlet and JSP performance tuning

Improve your enterprise application's performance by tweaking your servlets and JSPs

Do your J2EE applications run slow?
Can they sustain rising traffic? This article describes performance-tuning techniques (PTT) for developing high performance and scalable JSP (JavaServer Pages) pages and servlets.
That means building applications that are reasonably and consistently fast, and can scale up to the increasing number of users and/or requests. In this article, I walk you through the practical and proven performance-tuning techniques that will boost the performance of your servlets and JSP pages tremendously, thus improving the performance of your J2EE applications.
Some of these techniques apply during the development phase, i.e., while you design your application and write the code. And some of these techniques are configuration-related.

PTT 1: Use the HttpServlet init() method for caching data

The server calls the servlet's init() method after the server constructs the servlet instance and before the servlet handles any requests. It is called only once in a servlet's lifetime. init() can be used to improve performance by caching the static data and/or completing the expensive operations that need to be performed only during initialization.

For example, it is a best practice to use JDBC (Java Database Connectivity) connection pooling, which involves the use of the javax.sql.DataSource interface. DataSource is obtained from the JNDI (Java Naming and Directory Interface) tree. Performing the JNDI lookup for DataSource for every SQL call is expensive and severely affects an application's performance. Servlet's init() method should be used to acquire DataSource and cache it for later reuse:


public class ControllerServlet extends HttpServlet
{
private javax.sql.DataSource testDS = null;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
Context ctx = null;
try
{
ctx = new InitialContext();
testDS = (javax.sql.DataSource)ctx.lookup("jdbc/testDS");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public javax.sql.DataSource getTestDS()
{
return testDS;
}
...
...
}



PTT 2: Disable servlet and JSP auto-reloading

Servlet/JSP auto-reloading proves useful during the development phase because it reduces development time, as you do not have to restart the server after every change in the servlet/JSP. However, it is expensive in the production phase; servlet/JSP auto-reloading gives poor performance because of unnecessary loading and burdening on the classloader. Also, it may put your application in strange conflicts when classes loaded by a certain classloader cannot cooperate with classes loaded by the current classloader. So turn off auto-reloading for servlet/JSP in a production environment to receive better performance.

PTT 3: Control HttpSession

Many applications require a series of client requests so they can associate with one another. Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. To support applications that must maintain state, Java servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions. Sessions are represented by an HttpSession object, but a cost is involved while using it. An HttpSession must be read by the servlet whenever it is used and rewritten when it is updated. You can improve performance by applying the following techniques:


* Do not create HttpSessions in JSP pages by default: By default, JSP pages create HttpSessions. If you do not use HttpSession in your JSP pages, to save some performance overhead, use the following page directive to prevent HttpSessions from being created automatically when they are unnecessary in JSP pages:

<%@ page session="false"%>

* Do not store large object graphs inside an HttpSession: If you store the data in the HttpSession as one large object graph, the application server will have to process the entire HttpSession object each time. This forces Java serialization and adds computational overhead. The throughput decreases as the size of the objects stored in the HttpSession increases because of the serialization cost.

* Release HttpSessions when done: Invalidate sessions when they are no longer needed using the HttpSession.invalidate() method.

* Set session time-out value: A servlet engine has a default session time-out value set. If you do not either remove the session or use it for the time equal to the session time-out, the servlet engine will remove the session from memory. The larger the session time-out value, the more it affects scalability and performance because of overhead on memory and garbage collection. Try to keep the session time-out value as low as possible.



PTT 4: Use gzip compression

Compression is the act of removing redundant information, representing what you want in as little possible space. Using gzip (GNU zip) to compress the document can dramatically reduce download times for HTML files. The smaller your information's size, the faster it can all be sent. Therefore, if you compress the content your Web application generates, it will get to a user faster and appear to display on the user's screen faster. Not every browser supports gzip compression, but you can easily check whether a browser supports it and then send gzip-compressed content to only those browsers that do.

Here is the code snippet that shows how to send compressed content whenever possible:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{

OutputStream out = null
// Check the Accepting-Encoding header from the HTTP request.
// If the header includes gzip, choose GZIP.
// If the header includes compress, choose ZIP.
// Otherwise choose no compression.
String encoding = request.getHeader("Accept-Encoding");

if (encoding != null && encoding.indexOf("gzip") != -1)
{
response.setHeader("Content-Encoding" , "gzip");
out = new GZIPOutputStream(response.getOutputStream());
}
else if (encoding != null && encoding.indexOf("compress") != -1)
{
response.setHeader("Content-Encoding" , "compress");
out = new ZIPOutputStream(response.getOutputStream());
}
else
{
out = response.getOutputStream();
}
...
...
}



PTT 5: Do not use SingleThreadModel

SingleThreadModel ensures that servlets handle only one request at a time. If a servlet implements this interface, the servlet engine will create separate servlet instances for each new request, which will cause a great amount of system overhead. If you need to solve thread safety issues, use other means instead of implementing this interface. SingleThreadModel interface is deprecated in Servlet 2.4.

PTT 6: Use thread pool

A servlet engine creates a separate thread for every request, assigns that thread to the service() method, and removes that thread after service() executes. By default, the servlet engine may create a new thread for every request. This default behavior reduces performance because creating and removing threads is expensive. Performance can be improved by using the thread pool. Depending on the expected number of concurrent users, configure a thread pool by setting the values for minimum and maximum number of both threads in a pool and increments. At startup, the servlet engine creates a thread pool with number of threads in a pool equal to the minimum number of threads configured. Then the servlet engine assigns a thread from the pool to every request instead of creating a new thread every time, and returns that thread to the pool after completion. Using the thread pool, performance can drastically improve. If needed, more threads can be created based on the values for maximum number of threads and increments.

PTT 7: Choose the right include mechanism

There are two ways you can include files in a JSP page: include directive (<%@ include file="test.jsp" %>) and include action (). The include directive includes the specified file's content during the translation phase; i.e., when the page converts to a servlet. The include action includes the file's content during the request processing phase; i.e., when a user requests the page. Include directive is faster than include action. So unless the included file changes often, use include directive for better performance.

PTT 8: Choose the right scope in useBean action

One of the most powerful ways to use JSP pages is in cooperation with a JavaBeans component. JavaBeans can be directly embedded in a JSP page using the action tag. The syntax is as follows:

"package.className" type="typeName">




The scope attribute specifies the scope of the bean's visibility. The default value for scope attribute is page. You should select the correct scope based on your application's requirements, otherwise it will affect application performance.

For example, if you need an object only for a particular request, but your scope is set to session, that object will remain in memory even after you are done with the request. It will stay in memory until you explicitly remove it from memory, you invalidate the session, or the session times out as per the session time-out value configured with the servlet engine. If you do not select the right scope attribute value, it will affect the performance because of overhead on memory and garbage collection. So set the exact scope value for the objects and remove them immediately when finished with them.


Miscellaneous techniques

* Avoid string concatenation: The use of the + operator to concatenate strings results in the creation of many temporary objects because strings are immutable objects. The more you use +, the more temporary objects are created, which will adversely affect performance. Use StringBuffer instead of + when you concatenate multiple strings.

* Avoid the use of System.out.println: System.out.println synchronizes processing for the duration of disk I/O, and that can slow throughput significantly. As much as possible, avoid the use of System.out.println. Even though sophisticated debugging tools are available, sometimes System.out.println remains useful for tracing purpose, or for error and debugging situations. You should configure System.out.println so it turns on during error and debugging situations only. Do that by using a final Boolean variable, which, when configured to false, optimizes out both the check and execution of the tracing at compile time.

* ServletOutputStream versus PrintWriter: Using PrintWriter involves small overhead because it is meant for character output stream and encodes data to bytes. So PrintWriter should be used to ensure all character-set conversions are done correctly. On the other hand, use ServletOutputStream when you know that your servlet returns only binary data, thus you can eliminate the character-set conversion overhead as the servlet container does not encode the binary data.


Conclusion

The goal of this article was to present you with some of the practical and proven performance-tuning techniques that will boost the performance of servlets and JSP pages tremendously, thus improving the performance of J2EE applications.

BidVertiser