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
    "Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
    "Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    "IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
    Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
    Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
    "Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
    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.
    "MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
    "There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
    SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
    It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
    WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
    A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
    SYS-CON Events announced today that Evatronix 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. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
    Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
    To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
    An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...