12 most important J2EE Best Practices (2)

Source: Internet
Author: User
Tags xsl xslt websphere application server
12 most important J2EE Best Practices (2)-Linux general technology-Linux programming and kernel information. The following is a detailed description. 6. Always use session Facades when using the EJB component.

Never expose the entity bean directly to any user type. The object bean can only use the Local EJB interface (Local EJB interfaces ).

When using the EJB component, using a session Facades is undoubtedly the best practice. In fact, this general practice is widely applied to any distributed technology, including CORBA, EJB, and DCOM. Basically, the more underlying your application's "cross-region" is, the less time it takes to relay small pieces of data over multiple network connections. To achieve this goal, you can create a large-granularity Facades object, which contains the logic subsystem. Therefore, you can call a method to complete some useful business functions. This method not only reduces network overhead, but also greatly reduces the number of accesses to the database by creating a transaction environment for the entire business function in EJB.

The local EJB interface (used since the EJB 2.0 specification) provides a Performance Optimization Method for coexistence ejbs. The Local interface must be explicitly accessed by your application. This requires code changes and prevents application changes when configuring EJB in the future. Since the session Facades and the entire EJB contained in the session should be local to each other, we recommend that you use a local interface for the Entity bean after the session Facades. However, the implementation of session Facades itself (for example, stateless session bean) should be designed as a remote interface.

To optimize the performance, you can add a local interface to the session Facades. In most cases (at least in Web applications), your EJB client and EJB will coexist in the same Java Virtual Machine (JVM. In another case, if the session Facades is called locally, you can use the J2EE application server configuration optimization (configuration optimizations), such as "No Local Copies" in WebSphere ". However, you must note that these alternative schemes change the pass-by-value method from pass-by-value to pass-by-reference ). This may cause subtle errors in your code. When you want to use these solutions, you should consider their feasibility from the very beginning.

If you use a remote interface (instead of a local Interface) in your session Facades, you can also configure the same session Facades in J2EE 1.4 as a Web service in a compatible manner. This is because JSR 109 (Web Service deployment in J2EE 1.4) requires that the remote interface of the stateless Session bean be used as the interface implemented by the EJB Web service and EJB. This is worthwhile because it can increase the number of client types for your business logic.

7. Use stateless Session bean instead of stateful Session bean.

In this way, your system can withstand the wrong termination. Use HttpSession to store user-related statuses.

In our opinion, the concept of stateful Session bean is outdated. If you think about it carefully, a stateful Session bean is actually exactly the same as a CORBA object in architecture. It is nothing more than an object instance bound to a server, it depends on the server to manage its lifecycle. If the server is disabled, the object does not exist, and the client information of the bean does not exist.

The fault transfer (failover) provided by the J2EE application server for stateful session bean can solve some problems, but the stateful solution is not stateless and easy to expand. For example, in WebSphere Application Server, requests for stateless session beans are achieved through balanced loading of member clusters where stateless sessions are deployed. On the contrary, the J2EE application server cannot load stateful bean requests in a balanced manner. This means that the loading process of servers in your cluster will be unbalanced. In addition, using stateful Session bean will add some status to your application server, which is also a bad practice. This increases the complexity of the system and complicate the problem in the case of a fault. A key principle for creating a robust distributed system is to try to use stateless behavior.

Therefore, we recommend that you use the stateless Session bean Method for most applications. Any user-related status that needs to be used during processing should be transmitted to the EJB method in the form of parameters (and stored by using a mechanism such as HttpSession) you can also retrieve data from persistent backend storage (for example, by using an entity bean) as part of an EJB transaction. This information can be cached in the memory when appropriate, but it is potentially challenging to store this cache in a distributed environment. The cache is very suitable for read-only data.

In short, make sure that the scalability is taken into account from the very beginning. Check all ideas in the design and consider whether your application can run properly when it is running on multiple servers. This rule is applicable not only to the application code in the preceding situations, but also to MBean and other management interfaces.

Avoiding stateful usage is not just a recommendation for IBM/WebSphere, it is a basic J2EE design principle.

8. Use transactions managed by containers.

Learn about the two-phase commit transactions in J2EE and use this method instead of opening up your own transaction management. Containers are almost always better at transaction optimization.

Transactions managed by containers (CMT) provide two key advantages (which is almost impossible without container support): composable work orders and robust transaction behavior.

If your application code explicitly uses start and end transactions (maybe javax. jts. userTransaction or even a local resource transaction), and future requirements require a combination of modules (which may be part of code refactoring). In this case, you often need to change the transaction code. For example, if module A starts A database transaction, updates the database, then commits the transaction, and Module B performs the same processing, consider what happens when you try to use the above two modules in Module C? Now, Module C is executing a logical action, which actually calls two independent transactions. If Module B fails to be executed, the transaction of module A can still be committed. This is what we do not expect. If, on the contrary, both module A and Module B use CMT, Module C can also start A CMT (usually through the configuration descriptor ), in addition, the transactions in module A and Module B will be the hidden part of the same transaction, so that complicated code rewriting is no longer required.

If your application needs to access multiple resources in the same operation, you need to use two phases to commit transactions. For example, if you delete a message from the JMS queue and then update the Record Based on the message, it is especially important to ensure that both operations are executed or not executed. If a message has been deleted from the queue and the system does not update the records in the database related to the message, the system is unstable. Some serious customer and business disputes originate from inconsistency.

We often see some customer applications trying to implement their own solutions. The application code may be used to "undo" the queue operation when the database update fails. We do not advocate this. This implementation is much more complex than you initially thought, and there are many other situations (imagine a situation where an application suddenly crashes during the execution of this operation ). As an alternative, you should use two-phase commit transactions. If you use a CMT and access resources submitted in two phases in a single CMT (for example, JMS and most databases), WebSphere will handle all the complex work. It ensures that the entire transaction is executed or not executed, including system crashes, database crashes, or other situations. In fact, the transaction log stores the transaction status. When applications access multiple resources, we cannot emphasize the necessity of using CMT transactions.

9. Use JSP as the first choice for presentation layer.

XML/XSLT is used only when multiple types of output are required, and the output type is supported by a single controller and backend.

We often hear some arguments about why you choose XML/XSLT instead of JSP as the presentation layer technology. In the opinion of the person who chooses XML/XSLT, JSP "allows you to mix models and views" does not have this problem. Unfortunately, this is not entirely true, or at least not as clear as the white and black points. In fact, XSL and XPath are programming languages. XSL is Turing-complete, although it does not comply with the programming language defined by most people, because it is rule-based and does not have control tools that programmers are used.

The problem now is that since this flexibility is given, developers will take advantage of this flexibility. Although everyone agrees that JSP makes it easy for developers to add "similar models" to the view, in fact, the same thing may be done in XSL. Although it is very difficult to access the database from XSL, we have seen some extremely complex XSLT style sheets that execute complex conversions, which are actually model code.

However, the most basic reason for choosing JSP as the preferred Representation Technology is that JSP is currently the most widely supported and widely understood J2EE view technology. With the introduction of new features of the custom tag library, JSTL, and JSP2.0, it is easier to create JSP without any Java code, and the model and view can be clearly separated. Added strong support for JSP (including debugging support) in some development environments (such as WebSphere Studio), and many developers found that using JSP for development is easier than using XLS, some graphical design tools that support JSP and other features (especially in a framework like JSF) enable developers to develop JSP in WYSIWYG mode, XSL is sometimes not easy to do.

The last reason for using JSP is speed. Performance tests on the relative speed of XSL and JSP compared by IBM show that in most cases, JSP is several times faster than XSL when generating the same HTML, this is even true for compiled XSL. Although this is not a problem in most cases, it will become a problem in the case of high performance requirements.

However, it cannot be said that you should never use XSL. In some cases, XSL can represent a set of fixed data, and the ability to display data in different ways based on different style sheets is the best solution for displaying views. However, this is only an exception, not a general rule. If you only generate HTML to express every page, in most cases, XSL is an unnecessary technology, and, it brings far more problems to your developers than it can solve.

10. When using HttpSession, try to only save the status required by the current firm, and do not store other content in HttpSession.

Enable session persistence.

HttpSessions is useful for storing application status information. Its APIs are easy to use and understand. Unfortunately, developers often forget the purpose of HttpSession-to maintain the temporary user status. It is not an arbitrary data cache. We have seen too many systems put a large amount of data (in MB) into each user's session ). Well, if there are 1000 users logging on to the system at the same time, each user has 1 MB of session data, then 1 GB or more memory is required for these sessions. To make the HTTP session data smaller, otherwise, your application performance will decrease. A suitable data volume should be between 2 K-4 K for each user's session data. This is not a hard rule and 8 K is still correct, but it is obviously slower than 2 K. Be sure not to make HttpSession a place where data is accumulated.

A common problem is to use HttpSession to cache information that is easy to recreate, if necessary. Since sessions are persistent, it is a luxury to serialize unnecessary data and write data. On the contrary, you should use a hash table in the memory to cache data and save a keyword to reference the data in the session. In this way, if you cannot successfully log on to another application server, you can recreate the data.

When talking about session persistence, do not forget to enable this feature. If you do not enable session persistence or the server is stopped for some reason (Server failure or normal maintenance), the sessions of all current users of this application service will be lost. This is a very unpleasant thing. Users have to log on again and do something they have already done. Conversely, if session persistence is enabled, WebSphere automatically moves users (and their sessions) to another application server. The user does not even know that such a thing will happen. We have seen some unacceptable bugs in Local Code (not IBM code!) in product systems !) In this case, the above functions can still run well.

11. Use Dynamic Caching in WebSphere and the WebSphere servlet caching mechanism.

By using these functions, the system performance can be greatly improved, and the overhead is very small. The programming model is not affected.

The benefits of improving performance through caching are well known. Unfortunately, the current J2EE specification does not include a mechanism for servlet/JSP caching. However, WebSphere provides support for page and fragment caching, which is implemented through its Dynamic Caching function and does not need to be changed to the application. The cache policy is declarative, and its configuration is implemented through the XML configuration descriptor. Therefore, your application will not be affected and maintain compatibility and portability with J2EE specifications. At the same time, you will also get performance optimizations from the cache mechanism of WebSphere servlet and JSP.

The performance improvement from the Dynamic Caching mechanism of servet and JSP is obvious, depending on the characteristics of the application. Cox and Martin [Cox] point out that when Dynamic Caching is used for an existing RDF (Resource description format) site abstract (RSS) servlet, its performance can be improved by 10%. Note that this experiment only involves a simple servlet. The increasing performance may not reflect a complex application.

To improve performance more, the WebSphere servlet/JSP result Cache is integrated with the WebSphere plug-in ESI Fragment Processor, ibm http Server Fast Response Cache Accelerator (FRCA), and Edge Server Cache functions. The use of these features provides many additional benefits for heavy read-based workloads.

12. To improve the efficiency of programmers, the CMP Entity bean is the preferred solution for O/R ing.

Optimize performance through the WebSphere framework (readahead, cache, isolation level, etc. If possible, there are some application modes to improve performance, such as Fast-Lane reader [Marinescu].

Object/relationship (O/R) ing is the basis for creating enterprise-level applications using Java. Almost every J2EE application requires some type of O/R ing. J2EE vendors provide an O/R ing mechanism, which is portable and efficient among different vendors and can be well supported by some standards and tools. This is the CMP (persistence of Container Management) section in the EJB specification.

Early CMP implementations were known for their poor performance and lack of support for many SQL structures. However, with the emergence of EJB 2.0 and 2.1 specifications and adoption by some vendors, and the emergence of IBM WebSphere Studio Application Developer, these problems are no longer problems.

Cmp ejb components are now widely used in many high-performance applications. WebSphere provides some optimization functions to improve the performance of EJB components. The optimization functions include lifecycle cache and read-ahead capabilities. Both of the optimization functions are configuration options and do not need to modify the application or affect portability.

The CMP State data is cached in the cache life cycle and time-based invalidity is provided. The performance improvement from the cache lifecycle can achieve the cache performance of option A and still provide scalability for your applications. The Read-ahead capability is used in conjunction with container management. This feature allows you to randomly retrieve relevant data as the parent data in the same query to reduce interaction with the database. This method can improve performance if the related data needs to be accessed through concurrent queries. [Gunther] provides detailed descriptions and detailed performance improvements through these features.

In addition, to fully optimize your EJB components, pay special attention when specifying the isolation level. Try to use the lowest isolation level and maintain the integrity of your data. A lower isolation level can provide optimal performance and reduce the risk of database deadlocks.

This is currently the most controversial best practice. There have been a lot of articles praising cmp ejb, and the same criticism is endless. However, the most basic problem here is that database development is difficult. Before you start using any persistent solutions, you need to learn the basics of queries and how database locking works. If you choose to use cmp ejb, make sure that you know how to use them through books such as [Brown] and [Barcia. There are some subtle interactions that are hard to understand in terms of locking and competition, but it will be mastered after you spend some time and effort.

Conclusion

In this short summary, we have introduced you to the core mode and Best Practices in J2EE, which makes J2EE development a manageable process. Although we did not provide all the necessary details for using these patterns in practice, we hope to give you enough guidance and guidance to help you decide what to do next.
Related Article

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.