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
    From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
    When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
    SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
    IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
    Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
    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. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
    Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
    "We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
    Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
    SYS-CON Events announced today that Grape Up 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. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
    Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
    SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
    Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
    Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
    In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
    SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
    SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
    SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...