You are on page 1of 4

BY HARVEY GUNTHER

WEBSPHERE DEVELOPMENT

EJB Best Practices Applied


Taking advantage of EJB 2.0 local interfaces and Read-Ahead for CMRs
is an essential part of the Knowledge and Action pattern

I
n “J2EE Application Performance: Patterns and
Anti-Patterns” (March 2003 and article ID 3133
at e-ProMag.com), I showed that the Knowledge
and Action pattern is superior to the Dollars and
Desperation anti-pattern in solving J2EE application
performance problems. The Knowledge and Action
pattern examines the application’s core implemen-
tation for flaws and missing best practices for per-
formance and scalability. Here, I discuss the applied
best practices in more detail and also explain how
not to miss them in your own application.
The application in the previous article was a salary-
adjustment application used by a hypothetical busi-
ness called e-Gloom. This application consisted of
servlets, JSPs, EJB session beans, and EJB entity beans
using container-managed persistence (CMP). The
EJB session bean The Salary Adjuster modeled the
application’s behavior, and the EJB CMP beans pro-
vided the data persistence layer. The main EJB entity
beans were the Department, which aggregated FIGURE 1
e-Gloom application performance comparison
another entity bean, the Employee. There is a one-
to-many relationship between a Department and its
Employees. the entire application was single-threaded. All of the business
I developed the e-Gloom application for EJB 1.1 using WAS logic and more importantly all of the database accesses were
4.0. Here, I examine the benefits of upgrading the application single-threaded. As a result, only one user at a time could use
to EJB 2.0 using WAS 5.0. e-Gloom took advantage of two new the e-Gloom application. Consequently, the application could
WAS 5.0 EJB 2.0 best practices: (1) Use of EJB 2.0 local interfaces effectively use no more than one processor on a SMP machine.
and (2) use of EJB 2.0 Read-Ahead to Preload Association Data. Total synchronization like e-Gloom’s is rare, but synchroniza-
tion scalability remains a problem
e-Gloom’s Missed Best Practices for many applications. Because most
Article Profile
Due to inexperience, inadequate development processes, and applications are developed on lap-
a lack of performance methodology, the e-Gloom application tops or small desktop machines Focus: Apply the Knowledge and
Salary Adjuster missed a number of fundamental Best Practices with a single processor, development Action pattern to upgrade a hypo-
in its initial implementation. By fixing the application, I’ve ren- teams typically cannot detect syn- thetical business’s salary-adjustment
application.
dered a more significant performance benefit than I would have chronization problems until applica-
achieved by adding unlimited amounts of hardware. This is the tion integration on a test server, or Technology: J2EE Application
Knowledge and Action pattern. Development; EJBs
worse — not until the application is
The applicable Best Practices affected scalability and optimized deployed in production. Article ID number: 4616
the application’s database usage to reduce latency. Both of these As a normal part of application
areas are problematic for most applications. Here is how to avoid design reviews and code inspections,
falling in the same traps as e-Gloom: development teams should evaluate
About the Author
Avoid synchronizing the servlet’s major code path. Although and reduce, where possible, synchro- Harvey Gunther is a senior perform-
this Best Practice is well understood and near the top of every nization of major code paths. (See ance analyst for WebSphere Portal
for IBM Corporation. Harvey has
J2EE expert’s list, servlet synchronization and re-entrancy prob- “Development Processes for Enforcing
been with IBM since 1987 and has
lems still occur. Because servlets and JSPs are multi-threaded, Best Practices,” page 40.) Another focused on large-scale systems per-
their code must be either re-entrant or synchronized (i.e., single- essential development process for formance analysis.
threaded). The synchronization in e-Gloom’s code was so extreme, reducing synchronization and other

www.e-ProMag.com MARCH 2004 e-PRO MAGAZINE 39


E J B B E S T P R AC T I C E S

runtime performance and scalability problems is development • EJB 1.1 — Specifying non-Update methods as Read-Only
time benchmarking and profiling on a production-sized SMP to avoid database Update operations after a transaction
machine well before production. ends. The WAS EJB 1.1 container will avoid implicit data-
Wrap entity beans with session beans. Like avoiding syn- base updates if within the transaction, all the entity bean’s
chronization, this best practice is fairly well known. The key accessed methods are Read-Only. WAS provides a CMP
aspect of this best practice is that the session bean provides a Optimizer tool that simplifies and automates this process
single transaction context for the entity beans that are accessed for application deployment specialists.
within a transaction. • EJB 1.1 — Selecting the appropriate database transaction
Entity beans synchronize their states with the underlying isolation level. The default database transaction isolation level
data store at the start and the end of each transaction. If an for the WAS EJB 1.1 container is Repeatable Read, which locks
entity bean is accessed directly from a servlet or JSP, there is an entire result set to isolate each user of an application from
no active transaction. As a result, each entity bean method, conflicting database updates. Due to its design, the e-Gloom
such as a getter, becomes a new transaction requiring state application does not have database collisions between users, so
synchronization with the underlying data store. a lesser isolation level such as Read-Committed is appropriate.
As an example, consider an EJB CMP entity bean with seven • EJB 1.1 — Specifying finder methods as non-Update to avoid
properties. With no transaction active, client code that calls all “Select… For Update.” The WAS EJB 1.1 container will not use
seven entity bean “getter” methods in one logical action yields a SQL For Update clause on the Select statement for finder
14 database operations. With a session bean’s transactional methods (FindByPrimaryKey included) specified as Read-
context in place, the seven entity bean methods would pro- Only. By default, finder methods are not specified as Read-
duce at most two SQL statements: an SQL read for the associ- Only. (This default for finders is necessary to avoid deadlocks
ated row in the database table at the start of the session bean in certain situations by obtaining an update lock with a data-
method, and an SQL update at the end of the transaction estab- base read.)
lished by the EJB session bean method. This approach yields
both a significant database and an overall performance Improve relational database mapping for CMP entity
improvement. beans. e-Gloom’s original application used database bottom-
Improve EJB 1.1 deployment to optimize database access. up mapping to build CMP entity beans from the underlying
There are three improvements here: database tables. By default, this creates a CMP entity bean that

Development Processes for Enforcing Best Practices

T eam and Peer Application Design Reviews and Code Inspections.


These are valuable practices that help performance and a number
of other potential problems throughout the application development
often during the development cycle. If your team is using an iterative
development process, you should benchmark after each iteration as
soon as there is enough logic to support a benchmark. You should
cycle. Design reviews and code inspections also promote better team also profile benchmarks using an industrial strength profiler. The team
understanding and promote cross-pollination of ideas. Review of estab- should profile the application under load with multiple users. Another
lished best practices should be one key part of a design review and technique and artifact from benchmarking is the thread dump. Devel-
code inspection. opers can examine the raw thread dump or use an excellent WAS tool,
Thread Analyzer, to examine the state of the application server’s threads.
Database Design/Application Requirements Walk-Throughs. A bad Look for patterns where threads are in a wait state contending for locks
database design can ruin an application’s performance. Unnecessary or bogged down in database access.
tables or data columns will create extra and unneeded database over-
head. It is crucial for the application development and data adminis- Database Usage Profiling. One common technique for reducing data-
tration teams to have a clear and mutual understanding of what is base latency is to use database tools such as a DB2 snapshot to
required to reduce database latency. Sometimes, reduced database develop a database profile of the database. Database profiling is
normalization in the form of duplicate database columns will actually every bit as important as application profiling. Reviewing and acting
improve performance by reducing the number of entity beans and data on the database profile data is the joint responsibility of the applica-
accessed. However, keep in mind that redundant data can complicate tion development team and the data administration team. DB2 snap-
and slow update applications. shot tools produce a timed summary of all of the SQL statements
issued during a measurement interval. Iterative snapshots coupled
Early Benchmarks and Analysis on SMP Machines. The prevailing with caching and other positive actions can yield large benefits.
pattern is to delay this activity until pre-production or to avoid it alto-
gether. But you should benchmark embryonic applications early and — H.G.

40 e-PRO MAGAZINE MARCH 2004 www.e-ProMag.com


retrieves and updates every column in the underlying table. second. The points on the right-side y-axis apply to the line
In e-Gloom’s case, the application didn’t need to access every graph, which shows the performance response-time improve-
column in the table. e-Gloom was able to realize a significant ment. The bulk of the application performance improvement
reduction in database latency and related application perform- came from the unique WAS Read-Ahead feature (described
ance improvement by re-mapping the entity bean and table below). Figure 1 also includes comparison data points for the
relationship to include only those database columns that were un-optimized e-Gloom application (labeled “Original” in Figure
needed to support the application. This improvement was 1) as well as the best possible performance for EJB 1.1 on WAS 4.0.
reflected in the DB2 snapshot profile and overall performance Here are the new WAS 5.0 EJB 2.0 Best Practices that e-Gloom
metrics. used to improve the performance of its application:
De-normalize a table to eliminate an entire entity bean. Use of EJB 2.0 local interfaces. By definition, EJBs are loca-
e-Gloom’s application included a table, Appraisal, which con- tion-transparent; therefore, they require remote access. WAS V4
tained a row for each appraisal rating received by an
employee. e-Gloom developed an entity bean for Application-specific caching frameworks
the Appraisal table. Although e-Gloom’s application
required only each employee’s most recent appraisal,
closely tailored to specific application
the table included an appraisal for every year of requirements usually provide better
employment. The improved application added a
latest appraisal column to the Employee table and performance than generalized facilities.
dropped the entire Appraisal table and related entity
bean. This reduced both database latency and also
application path length by reducing the number of entity beans provides a configurable optimization for passing EJB parameters
accessed for a transaction. and return values by reference, which can improve performance.
Seize opportunities for caching. e-Gloom’s application has However, the EJB is still treated as a remote object. The EJB 2.0
two tables that provide the foundation of the Salary Adjustment specification allows an EJB to be defined with a local interface
application: that specifies that the EJB is local to the same EJB container as the
client and is not location-transparent. A good pattern applicable
• The Salary Guidelines table governs the amount of raise
to e-Gloom is to specify local interfaces for all entity beans while
based on current employee appraisal level.
maintaining session beans as location-transparent (i.e., remote
• The Salary Range table shows Salary Range by Job
interfaces) to allow for future WAS clustering opportunities.
Description.
Selectively use EJB 2.0 CMP Read-Ahead for associated
Both of these tables are small. e-Gloom’s original application data. WAS provides for preloading of associated data specified
implementation accessed both of these tables for each transac- by container-managed relationships (CMRs). This is particularly
tion. However, this information is generally static for the period useful for e-Gloom’s application, which depends on a relation-
of time that the application is in use for computing salary adjust- ship between the Department entity bean and the associated
ments. Most companies compute salary ranges and raise formu-
las annually. They are static for a year and do not change during
the operational use of e-Gloom’s application. Also, the small size
of the tables enabled e-Gloom to cache the data in both tables Further Reading
in their own homegrown caching framework, the Salary Grid.
e-Pro Magazine Articles at e-ProMag.com
Application-specific caching frameworks such as the Salary
“Tuning WebSphere Application Performance”
Grid provide better performance and have less overhead than
February 2003, article ID 3015
generalized EJB Container caching facilities such as “Option A”
and the new WAS 5.0 “Lifetime in Cache.” Both of these WAS- “Rev Up WebSphere V5 Performance”
based facilities reduce database accesses and related overhead. May 2003, article ID 3401
However, both require some EJB Container overhead. Application-
specific caching frameworks closely tailored to specific applica- Book
tion requirements usually provide better performance than Performance Analysis for Java Web Sites (Addison-Wesley, 2003)
generalized facilities.
IBM White Paper
Upgrading to WAS 5.0 and EJB 2.0 “WebSphere Application Server Development Best Practices for
As e-Gloom migrated from WAS 4.0 EJB 1.1 to WAS 5.0 EJB 2.0, it Performance and Scalability,” IBM White Papers at www-3.ibm
exploited new opportunities for performance. Figure 1 (page 39) .com/software/webservers/appserv/ws_bestpractices.pdf or
is a dual metric performance graph that shows the performance www-3.ibm.com/software/webservers/appserv/performance
improvement for the e-Gloom application. The points on the .html.
left-side y-axis apply to the bar graph, which shows the per-
formance throughput improvement in terms of requests per

www.e-ProMag.com MARCH 2004 e-PRO MAGAZINE 41


E J B B E S T P R AC T I C E S

Employee beans that represent employees that work in the extremely careful before using wsPessimisticUpdateNo-Collisions
department. EJB 1.1 does not have CMR, a feature that was because it provides no protection against conflicting updates
introduced in EJB 2.0. With Read-Ahead, when the container among multiple concurrent users.
retrieves the database data for a particular bean in a Find by WAS provides seven pre-defined access intents. WAS Enterprise
Primary Key operation, the container also retrieves the associ- allows for the definition of application-specific application pro-
ated data in one SQL Select statement using a join. Read-ahead files and access intents. For a complete explanation of WAS 5.0
is an optional configured feature which is not a default. EJB 2.0 access intents and application profiles, see the “Using
Applied to e-Gloom, Read-Ahead will retrieve the employees access intent policies” topic in the WAS and WAS Enterprise
in a department when the application retrieves the department. InfoCenters.
This is an important optimization for e-Gloom. e-Gloom’s appli- One other WAS V5 improvement is that the EJB 2.0 container
cation pattern is to retrieve the department and then process tracks CMP entity bean updates and automatically avoids data-
base updates when a bean is updated. Unlike with
Access intents are fundamental to providing EJB 1.1, application deployment specialists need
not take any additional steps to avoid unnecessary
database and application integrity for EJB 2.0 database updates for EJBs.
applications. Improved by Knowledge and Action
e-Gloom was able to achieve significant improve-
salary adjustments for all the employees. Retrieving the depart- ment in a poorly written application by using the Knowledge
ment and all its employees in one SQL Select yields a consider- and Action pattern. Positive practices such as formal design
able performance optimization by reducing the number of reviews, code inspections, development-time benchmarking,
database accesses. In a department with 10 employees, EJB and application profiling are core to the Knowledge and Action
processing without Read-Ahead requires 11 database SQL pattern. Taking advantage of new performance optimizations in
Select operations; with Read-Ahead, it requires only one SQL newer WAS releases such as EJB 2.0 local interfaces and Read-
Select (across two tables). Ahead for CMRs is likewise an essential part of the Knowledge
The e-Gloom application’s relationship between the depart- and Action pattern. There are always opportunities for applica-
ment bean and employee bean was an ideal case for using Read- tion performance improvements. To learn more about improv-
Ahead. Every access of the department bean required access of ing Web application performance, check out the resources in
all of its employees. There was no situation in which the appli- Further Reading, page 41. ❍
cation retrieved a department without its employees. The depart-
ment and employee relationship was the major component of I’d like to acknowledge Alice H. Gunther for providing the domain
e-Gloom’s processing. expertise for the e-Gloom salary adjustment application, Ruth
Other applications with different access patterns might not E. Willenborg for her book on Java performance (see Further
see similar benefit. Still, Read-Ahead is an important new WAS Reading) and her help with this article, and Tom Alcott for
feature that should provide a unique benefit to most applica- partnering with me on the e-Gloom presentations over the
tions with CMRs. past two years.
Use the correct EJB 2.0 access intents for the application’s
needs. The WAS 5.0 EJB 2.0 container introduces a new facility —
access intents — to help application deployment specialists
specify (1) the right isolation level and (2) whether “SELECT
For-Update” should be specified on the SQL Select statement.
Access intents are also based on the underlying database man-
agement system implementation.
Access intents are fundamental to providing database and
application integrity for EJB 2.0 applications. No one should
ever scrimp on database and application integrity for perform-
ance. Likewise, no one should ever pay the cost for a level
of integrity not required by the application.
In e-Gloom’s application, there was no possibility of database
update collisions. The application was structured in such a way
that only the department manager could access and update the
employee salary records for his or her department. For e-Gloom’s
application on WAS 5.0 EJB 2.0 and DB2, the appropriate access
intents are either wsOptimisticUpdate or wsPessimisticUpdate
No-Collisions, both of which specify Read Committed isolation
level and do not use SELECT-FOR-UPDATE. You should be

42 e-PRO MAGAZINE MARCH 2004 www.e-ProMag.com

You might also like