Performance Improvement in J2EE applications

Source: Internet
Author: User
Tags abstract definition
Java is very popular. Although it was born for only nine years, it has become one of the world's leading development environments. Millions of programmers and thousands of companies are using it, and half of IT managers want to deploy J2EE applications this year.

However, the popularity of Java does not necessarily make it easier for growing Java code developers. In order to reach a new height in production, programmers gradually work in larger teams, and among them, the continuous shortening of the development cycle is always very popular. Every day, those teams face the same law in software development: the more code you write, the more bugs you encounter, the time-wasting and the bug that reduces application quality and performance.
This article mainly introduces the performance tuning and memory usage optimization of a J2EE application. We set to use BEA WebLogic application server. We will discuss the following aspects:

  • Problem domain
  • Optimize a Java VM
  • HTTP session management
  • Application Server Tuning
  • Encoding standard: Give up rules for the future

Problem domain
We have a J2EE application with the following settings:

  • BEA WebLogic 6.1 Service Pack 5 serves as an application/Web server.
  • A popular RDBMS. This does not affect our discussion.
  • Model I Web architecture.
  • Eight stateless ejbs and six stateful ejbs.
  • HTTP session has reference to stateful EJB.
  • The database connection pool is initialized to 2 and the maximum value is 10.
  • There are about 120 servlets on the web layer.
  • XML/XSLT-based architecture.

Problem
The application has a memory issue. When the server is started, memory usage accounts for about 7 of the total available physical memory ~ 8%. As time passes and more applications are used, the memory usage will increase to nearly 49 ~ 53% (7 ~ 10 days per cycle ).
If a user cancels a session by clicking the "log off" button in the left menu, the application deletes all stateful beans from the server. However, if a user just closes the browser window, it will not delete those beans, but will keep them in the container until the application server restarts. In this way, the number of EJB instances in the memory will increase to 400 or more.
When BEA WebLogic Server loads more than 400 ejbs, the hotspot Virtual Machine throws an outofmemory exception. Although it seems that more memory is available, this still happens.

Optimize a Java VM
When trying to allocate permgeneration space, the hotspot virtual opportunity throws an outofmemory exception. The hotspot virtual machine uses different parts of memory. The permanent generation part is used to store the symbols used by classes, methods, and running Java objects. The initial size of the permanent generation part is 1 MB, the maximum value is 64 MB, and 32 MB before 1.3.1.
To avoid this situation, you can use the following command line to set the permgeneration space through a Java Virtual Machine switch.
Java-server-XX: maxpermsize = 128 M.
Note that increasing the maximum perm value only delays the occurrence of a fault. In the end, it is still necessary for your application to properly clear useless objects. In addition, not all Java virtual machines support the XX option.

HTTP session management
When the browser is closed without being deregistered from the session, the EJB in the session will not be garbage collected. This is the main reason why there are too many ejbs in the memory. To avoid this situation, you must pay attention to all possible combinations of HTTP session management. You can set a default session timeout period in Web. XML (Web application deployment descriptor), as shown below:

<Session-config>
<Session-Timeout> x </session-Timeout>
<Session-config>

With this setting, your sessions will be automatically released after being inactive for X minutes.
Another method is to write session management with the following code when creating an http session.

Httpsession session = new httpsession ();
Session. setmaxinactiveinternal (INT timeoutseconds );

This code will invalidate user sessions that are not active for timeoutseconds.
Note: If you have done both steps, the values in the servlet code will overwrite the values set in Web. xml.
The only difference between the two methods is that the second method uses seconds as the parameter, while the <session-Timeout> flag uses minutes as the parameter. Generally, when a session fails, logoff Servlet/jsp deletes the reference of all objects/object images referenced by a special session using code. However, when the user only closes the browser, there is no way to call the logout Servlet/JSP. In this case, even if the session has expired, the encapsulated object and object graphics will continue to exist. When the garbage collector tries to collect garbage for this session, it also collects all these encapsulated objects. When we have large objects (objects with large references/data), we can also use the httpsessionlistener interface to clear the objects.

Javax. servlet. http. httpsessionlistener Interface
This interface declares the following two callback methods:

Public void sessioncreated (httpsessionevent event );
Public void sessiondestroyed (httpsessioneven event );

These methods are called before a session is created/destroyed.
We can use a listener class that implements this interface and use these callback methods to control the creation and destruction of sessions. We need to register our listener class in Web. XML as follows:

<Listener>
<Listener-class> mysessionlistener </listener-class>
</Listener>

The advantage of using the listener class and adding the Session Timeout parameter to the Web. xml file is that we can control session management more. If a session has large objects, its time slice may disappear before the Garbage Collector clears these objects. In this case, you need to wait until the next time slice to clear these objects.
Note: It is very important that the application we designed has only one entry point. We need to start a new http session in this class. Check whether the http session exists on all remaining pages, and call an error page when the session is null (the session expires. This enables centralized control over HTTP sessions.

Application Server Tuning
BEA WebLogic provides some parameters that can be used to optimize the size of the bean pool, including setting the initial size of the stateless bean pool. Here are some usage methods:

  • Set the minimum value of the bean pool with <initial-bean-pool-size> marked as stateless Session Bean: 1000 by default. Because stateless session beans can be shared among concurrent users, it is best to set this value to a very small value. The proper value of this tag depends on the concurrent user and the peak loading of the application.
  • Set the maximum value of the bean pool with <max-beans-in-free-pool> As a stateful Session Bean: its default value is not specified. The value set by this flag will greatly affect the activation and passivation mechanism of BEA WebLogic Server. The proper value depends on the application traffic. When the number of beans in the pool reaches the threshold and another request to the new bean instance arrives, the WebLogic Server selects one or more beans in the pool to deactivate them. The algorithm used to select bean instances for passivation is LRU (least recently used) or NRU (not used recently ).
    If Max-beans-in-cache is reached and the EJB in the cache is not in use, the WebLogic Server will deactivate some of the beans. Even though useless beans have not reached their idle-timeout-seconds limit, this also happens. If Max-beans-in-cache is reached and the EJB in the cache is being used by the client, the WebLogic Server will throw a cachefullexception exception.
  • Use the <idle-timeout-seconds> flag to set the WebLogic Server's waiting time before inactivating an idle stateful Session Bean instance: the Weblogic server will be in the SWAp) wait for the same amount of time before deleting the bean in the space. You should be careful to set this value, because once the passive instance is deleted from the swap space, there is no way to re-obtain the bean status.

For example, consider the following settings

<Idle-timeout-seconds> 1200 </idle-timeout-seconds>

The idle bean instance will be deactivated after being static for 20 minutes. In another 20 minutes, the bean instance will be deleted from the hard disk. Now, let's assume that the user called a method of this bean instance in 41st minutes. BEA WebLogic Server throws an error, as shown in program list 1.

Program list 1
: Bean has been deleted.
At weblogic. ejb20.swap. diskswap. Read (diskswap. Java: 156)
Weblogic. ejb20.manager. statefulsessionmanager. getbean (statefulsession manager. Java: 242)
Weblogic. ejbworkflow manager. statefulsessionmanager. preinvoke (statefulsessionmanager. Java: 313)
At weblogic. ejb20.internal. baseejblocalobject. preinvoke (baseejblocalobject. Java: 113)
At
Weblogic. ejb20.internal. statefulejblocalobject. preinvoke (statefulejblocalobject. Java: 126)
WebLogic 6.1 Service Pack 5 provides a useful tag to avoid this situation. The mark is as follows:
<! -- The stateful session beans that are passivated to the disk will stay alive for this hour 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 a value for this <session-timeout-seconds>, we can control when the passive bean is deleted from the hard disk. We can use this flag and set it to an appropriate value so that we can always have stateful ejbs (either in memory or on hard disks ). This completely eliminates bean deletion errors.

Use WebLogic managed Server
BEA WebLogic allows you to create one or more servers in a single domain. One Server is a management server, and all other servers are managed servers, that is, managed servers. Once an application is put into use, it should not be deployed on the management server. The advantage of using managed servers is that we can start and stop them from the Management Console. Therefore, even if the server causes the application to stop responding (for any reason), we still have the opportunity to restart the server from the console.
Encoding standard: Give up rules for the future
It is more difficult to manage a development system when the system runtime environment is not considered in the design phase. After the environment, boundaries, and application running environment are carefully considered in the design stage, re-development of the system is a simple task. Design is the abstract definition of the execution path. When every detail in the design is taken into account before development, the solution will be more scalable. There are no hard rules for system development, because it depends on the specific problem domain you are facing. However, there are still some laws that will always be helpful.

  • You must have a clear understanding of complementary classes such as string and stringbuffer:Use the appropriate class when appropriate. For example, constructing a long SQL query using the string class is very inefficient and increases the load on the JVM string pool.
  • Clear the inherited objects immediately after they are used, such as hashtable.
  • Explicitly call the remove () method in the EJB reference:This releases the bean instance to the bean pool and reduces the number of bean instances created by the container.
  • Manage database connections with caution:Call the close () method immediately after use. Do not open the connection in the first line of the class. The connection is enabled only when necessary.
  • Understand business needs,You can understand the code execution environment before writing the first line of code.

In a word, "create objects as late as possible and delete them as early as possible ".

Source http://www.sys-con.com/story? StoryID = 43039 & De = 1

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.