| By GVB Subrahmanyam, Shankar Itchapurapu | Article Rating: |
|
| December 1, 2003 12:00 AM EST | Reads: |
22,206 |
Java is hot. Just nine years old, it has become one of the leading development environments in the world. Millions of programmers and thousands of companies use it, and half of all IT managers expect to deploy J2EE applications this year.
But Java's popularity hasn't necessarily made it easy for the growing population of Java code jockeys. Ever-shortening production cycles have kept the heat on programmers, who increasingly work in large teams to meet production milestones. And every day those teams come face-to-face with an immutable law of software development: the more code you write, the more bugs you'll get - bugs that cost time and sap quality and performance from applications.
This article looks at performance tuning and optimization of memory usage of a J2EE application. Our setup uses the BEA WebLogic Application Server. We will consider the following:
- The problem domain
- Tuning the Java Virtual Machine
- HTTP session management
- Tuning the application server
- Coding standards: laying ground rules for the future
The Problem Domain
We have a J2EE application with the following setup:
- BEA WebLogic 6.1 Service Pack 5 as application/Web server.
- Some popular RDBMS. This has no effect on our discussion.
- Model I Web Architecture.
- Eight stateless EJBs and six stateful EJBs.
- HTTP session holding references to stateful EJBs.
- Database Connection Pool with initial size 2 and maximum size 10.
- Around 120 servlets in the Web tier.
- XML/XSLT-based architecture.
The Problems
There was a memory issue with the application. When the server was started, the memory usage was around 7-8% of the total physical memory available. As the days went by and the application went into wider use, the memory usage grew to nearly 49-53% (over a 7-10 day period).
If the users logged off from their session by clicking the "Log off" button in the left-hand side menu, the application removed all the stateful beans from the server, but if a user just closed the browser window it didn't remove those beans and stayed in the container until the application server was restarted. As this continued, the number of EJB instances in memory shot up to 400 and above.
When BEA WebLogic Server loads more than ~400 EJBs, the Hotspot VM throws an OutOfMemory Exception. This occurs even though there appears to be more memory available.
Tuning the Java Virtual Machine
The Hotspot Virtual Machine was throwing an OutOfMemory Exception while trying to allocate PermGeneration space. The Hotspot VM uses different sections of memory. The permanent generation section is used for storing classes, methods, and symbols used by running Java objects. The initial size of the permanent generation section is 1 MB and the maximum size was 32 MB prior to 1.3.1 and 64 MB.
To get around this, we can set up the permGeneration space through a JVM switch with the following command line:
java -server -XX:MaxPermSize=128M.
Note that increasing the max perm size only delays a failure. It's up to your application to properly clean the unused objects. Also, the XX options are not supported across all JVMs.
HTTP Session Management
When the user closes the browser without logging off from the session, the EJBs in the user's session will not be garbage collected. This is the primary reason for having too many EJBs in memory. To get around this, the HTTP session management has to look into all possible combinations. We can set up a default session time-out period in web.xml (Web application deployment descriptor) as follows:
<session-config>
<session-timeout>x</session-timeout>
<session-config>
With this setting, the user's session will be automatically deactivated after x minutes of inactivity.
The other way is to code the session management using the following code when creating HTTP session
HttpSession session=new HttpSession ();
session.setmaxinactiveinternal(int timeoutSeconds);
This code will invalidate the user's session of timeoutSeconds of inactivity.
Note: If you do both of these steps, the value in the servlet code will override the value set up in the web.xml.
The only difference between these two methods is that the second one takes seconds as the parameter while the <session-timeout> tag value takes minutes as the argument. Normally, when the session is invalidated the logoff servlet/JSP will have code to remove references to all objects/object graphs referenced by the particular session. But when the user just closes the browser button there is no way our logoff servlet/JSP will be called. In this scenario, even though the session is invalidated, the enclosed objects/object graphs will still be there. When the garbage collector tries to garbage collect this session, it will also have to garbage collect all of these enclosed objects. When we have large objects (objects with larger references/data), we can also use the HTTPSessionListener interface to perform some clean-up action.
javax.servlet.http.HTTPSessionListener Interface
This interface declares the following two call-back methods:
Public void sessionCreated(HttpSessionEvent event);
Public void sessionDestroyed(HttpSessionEven event);
These methods are called before a session is created/destroyed.
We can have a listener class that implements this interface and use these callback methods to control how sessions are created/destroyed. We need to register our listener class in the web.xml as follows:
<listener>
<listener-class>MySessionListener</listener-class>
</listener>
The advantage of using listener class along with the session timeout parameter in the web.xml file is that we will have more control of session management. If the session has large objects, then before the garbage collecter cleans up the objects, its time slice may disappear. In this case, it needs to wait for the next slice to clean up the objects.
Note: It is important that we design the application so that there is a single entry point. We need to start a new HTTP session in this class. All the remaining pages should check for the existence of HTTP session and for an error page when the session is null (Session Expired). This enables centralized control of HTTP sessions.
Tuning the Application Server
BEA WebLogic offers a number of parameters that we can set to optimize the bean pool size, including setting the initial size of the stateless bean pool. Some of the features include:
If max-beans-in-cache is reached and EJBs in the cache are not being used, WebLogic Server passivates some of those beans. This occurs even if the unused beans have not reached their idle-timeout-seconds limit. If max-beans-in-cache is reached and all EJBs in the cache are being used by clients, WebLogic Server throws a CacheFullException.
For example, consider the following setting:
<idle-timeout-seconds>1200</idle-timeout-seconds>
The idle bean instances will be passivated after 20 minutes of inactivity. After another 20 minutes, the bean instance will be removed from the disk also. Now let's say at the 41st minute the user has called a method on the bean instance. The BEA WebLogic Server will throw the error shown in Listing 1.
WebLogic 6.1 Service Pack 5 provides a useful tag to get around this. The tag is described as follows:
<!-- The stateful session beans that are passivated to the disk will stay alive for this many seconds. After this interval, the passivated beans will be removed from the disk.
Used in: stateful-session-cache
Since: WebLogic Server 6.1 sp5
Default value: 600
-->
<! ELEMENT session-timeout-seconds (#PCDATA)>
If we set the value for this <session-timeout-seconds> we can control the time the passivated beans will be removed from the disk. We can use this tag and set it to a very value so that we will always have our stateful EJBs (either in memory or on the disk). This will completely eliminate the bean deleted error.
Using WebLogic Managed Servers
BEA WebLogic allows you to create one or more servers within a single domain. One server will be the admin server; all other servers will be managed servers in the sense that they are managed by the admin server. An application, when put into production, should not be deployed in the admin server. The advantage of using managed servers is that we can start and stop them from the admin console. Thus even if the server holding the application stops responding (for any reason), we still have a chance to restart the server from the admin console.
Coding Standards: Laying Down the Rules for the Future
Managing a production system is even more difficult when the environment in which the system will run has not been taken into account in the design phase. System re-engineering is a simple task when careful consideration of the environment, boundaries, and context of the application is taken care of during the design phase. Design is an abstract definition of execution path. Solutions will be more scalable when the development is done by taking into account every minute detail of the design. There will be no hard and fast rules for system development as this depends on the particular problem domain in hand. But, there are some axioms that always help.
To sum up... "Create Objects as late as possible and remove them as early as possible".
Published December 1, 2003 Reads 22,206
Copyright © 2003 Ulitzer, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
Related Links
More Stories By GVB Subrahmanyam
As an Application Developer, Lead, Project Manager, and Development Manager and Delivery Manager in a wide variety of business applications as part of IT service provider, I am into delivery of solutions with most of the time with Banking/Finance domain/Supply Chain mgmt in the areas of Order to Cash, Procure to Pay, Inventory management, Structured products of financial systems, Post equity settlement and financial derivative confirmations. Major focus areas are Development, Delivery and Sustenance of IT Applications in Supply Chain/Insurance/Banking/Finance. Albeit most of my projects are Java based assignments, I am technology agnostic. In the current role, I am working as solution provider for Commercial Healthcare, Insurance, banking and Financial systems. I am also PMI Volunteer for OPM3 standard as this will help to understand latest process standards being adopted by PMI. Well, I have M.Tech. and Ph.D. from IIT Kharagpur in the area of Chemical Technology, India and MS in Software Systems from BITS Pilani. I am also PMI certified PMP. It is interesting that I have gone through one year program of Executive Program in Business Management from IIM Calcutta which has given me in sight into some of the management fundamentals and understanding concepts.
More Stories By Shankar Itchapurapu
Shankar Itchapurapu is a software engineer at BEA Systems, India. He holds a Master's degree in Computer Applications. You can e-mail Shankar at shankar.itchapurapu@gmail.com.































Ulitzer content is offered under Creative Commons "Attribution Non-Commercial No Derivatives" License.
For any reuse or distribution, you must make clear to others the license terms of this work.
The best way to do this is with a link to this web page.
Any of the above conditions can be waived if you get written permission from Ulitzer, Inc., the copyright holder.
Nothing in this license impairs or restricts the author's moral rights.