Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Performance Improvement in a J2EE Application

Kill the bugs that sap time and productivity

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:

  • Use the <initial-bean-pool-size> to set it to minimum possible value for stateless session beans: By default, the value is 1000. As stateless session beans can be shared between concurrent users, it is better to set this value to a very minimum. The correct value for this tag depends upon the concurrent users and peak load situation of the application.

     

  • Use the <max-beans-in-free-pool> tag to set the maximum bean pool size for the stateful session beans: The default value for this has no limit. The value set for this tag greatly affects the activation/passivation mechanism of BEA WebLogic Server. The appropriate value for this tag depends on the application's traffic. When the number of beans in this pool has reached the threshold and a request for a new bean instance has come, the WebLogic Server will pick one or more beans for this pool for passivation. The algorithm for picking up the bean instance for passivation is either LRU (Least Recently Used) or NRU (Not Recently Used).

    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.

     

  • Use the <idle-timeout-seconds> tag to set the time the WebLogic Server will wait before passivating an idle stateful session bean instance: The WebLogic Server will wait for the same amount of time before removing the bean from the swap space. Care should be taken in setting this value because once the passivated instance is removed from the swap space, there is no way to retrieve the state of the bean again.

    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.

  • Have a clear idea about supplementary classes like String and StringBuffer: Use the appropriate class in appropriate situations. For example, using String class to build a long SQL query is inefficient and overloads the JVM string pool.
  • Clean up legacy objects like Hashtable as soon as you're done with them.
  • Call remove() method on EJB references explicitly: This will release the bean instance to the bean pool and reduce the number of bean instances created by the container.
  • Manage database connections carefully: Have a close() method called on them as soon as you're done with it. Don't open the connection as a first line in the class. Open the connection only when you need it.
  • Understand the business requirements and the context in which your code executes before you write a single line of code.

    To sum up... "Create Objects as late as possible and remove them as early as possible".

  • More Stories By Shankar Itchapurapu

    Shankar Itchapurapu is a software engineer at Oracle in India. He holds a Master's degree in Computer Applications. You can e-mail Shankar at [email protected]

    More Stories By GVB Subrahmanyam

    GVB Subrahmanyam an Application Developer, Lead, Project Manager, Development Manager and Delivery Manager in a wide variety of business applications as part of an IT service provider. He focuses on Development, Delivery and Sustenance of IT Applications in Supply Chain/Insurance/Banking/Finance. Albeit most of his projects are Java-based assignments, he is technology agnostic.

    In his current role, Subrahmanyam is working as a solution provider for Commercial Healthcare, Insurance, banking and Financial systems with Mahindra Satyam. He is also TOGAF certified Enterprise Architect and IBM certified Ratioanal Software Architect.

    GVB Subrahmanyam has an M.Tech. and Ph.D. from IIT Kharagpur in the area of Chemical Technology, India and MS in Software Systems from BITS Pilani. He is also a PMI certified PMP. He attended one year of the Executive Program in Business Management(EPBM) from IIM Calcutta.

    Comments (1) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    Naveen 12/08/03 10:42:17 AM EST

    Excellent article, very informative and useful in real time.

    @ThingsExpo Stories
    Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
    SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
    Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
    Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
    SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
    SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
    In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
    SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
    With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
    Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
    Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
    As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
    Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
    Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant th...
    SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
    SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
    SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.