KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best...

26
J2EE Application Performance Management KEY DEVELOPMENT & DEPLOYMENT CONSIDERATIONS

Transcript of KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best...

Page 1: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

J2EE Application Performance Management

KEY DEVELOPMENT & DEPLOYMENT CONSIDERATIONS

Page 2: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

VERSION 2 1

I N T E R N A L D O C U M E N T

Introducing the VERITAS “J2EE Expert Series”

WHAT IS THE “J2EE EXPERT SERIES?”

The VERITAS “J2EE Expert Series” is a yearlong educational program designed byVERITAS and developed in concert with the Pearson Technology Group. The programprovides expert content on topical J2EE development and deployment concerns with a focuson application performance management. The foundation of the program is a custom e-book. The e-book consists of twelve unique chapters from twelve different books. Eachmonth a new chapter will be released and promoted. VERITAS will also conduct a Webcasteach month with one or multiple authors. Each Webcast will focus on the specific content ofthe chapter released that month and will provide a forum to ask industry experts topical J2EEquestions.

CONTENT OF THE E-BOOK

Unlike more traditional e-books that offer content from a single book, the e-book from the“J2EE Expert Series” is a compilation of content from twelve different books and over thirtydifferent authors. The e-book is broken up into three different sections, each focusing on adifferent aspect of J2EE development and deployment.

SECTION ONE: ARCHITECTING AND ANALYZING J2EE™ PERFORMANCE

J2EE application developers are faced with many challenges in successfully designing,developing, and deploying J2EE applications. One challenge is to understand the J2EEstandard and the variety of J2EE component "building blocks" that are available toapplication architects. Another challenge is to combine these building blocks into a specificapplication. These challenges sometimes involve competing concerns of developerproductivity and ease of maintenance with performance and scalability. Best practices forbalancing development concerns with performance and scalability are described in thissection.

Chapter 1 J2EE/EJB: A Case Study of an Industry-Standard Computing InfrastructureThis chapter describes the J2EE architecture and how the various components of thearchitecture interact. The performance impact of various architectural tradeoffs is alsodiscussed.

Chapter 2 Addressing Performance

Page 3: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

2

This chapter describes the role of performance in design. EJB specific issues such asminimizing remote calls, optimizing entity bean persistence, and managing transactions arepresented.

Chapter 3 Common Bottleneck SymptomsThis chapter discusses how to recognize and eliminate common patterns of underutilization,bursty utilization, high utilization, and uneven cluster loading. The symptoms of each patternare discussed along with the diagnostic techniques used to identify it and the steps neededto resolve the problem behind the symptoms.

SECTION TWO: CORE J2EE™ APPLICATION COMPONENTS

This section presents the various core J2EE components most commonly developed byJ2EE application developers. Servlets, Java Server Pages, Enterprise Java Beans, XML, andWeb Services are the building blocks that are used to construct J2EE applications. Each ofthese building blocks presents the application developer with a wide variety ofimplementation strategies. Best practices for developing these components with an eye onperformance and scalability is discussed.

Chapter 4 ServletsThis chapter discusses Servlet design and coding techniques that can affect performance.

Chapter 5 Advanced JSP and XML TechniquesThis chapter begins by examining how to access a Web service from within an HTML page.Next, the chapter discusses encoding issues and ways of processing large XML documents.Following that, some useful aspects of the two XML-related tab libraries that can be found inthe new Jakarta tag library will be highlighted.

Chapter 6 Optimizing JavaStop PerformanceThis chapter will focus on tuning the Java code and Oracle8i. It also shows you some basicstrategies that can be used for tuning your operating system for an e-commerce application.

Chapter 7 Session BeansThis chapter begins with a general discussion of EJB then looks at how session beans aremodeled in the Unified Modeling Language (UML). The chapter next discusses the keytechnological aspects of session beans.

Chapter 8 Building Application Servers with Enterprise JavaBeansThis chapter begins by describing how various types of EJBs work. It then discusses designand implementation of a sample application along with scalability and performance hints.

Chapter 9 Business Tier Design Considerations

Page 4: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

3

This chapter discusses Business Tier Design Considerations and Business and IntegrationTiers Bad Practices. Examples of the issues addressed are when to use stateful versusstateless session beans and the scalability impact of this decision.

Chapter 10 Using SOAP for eBusinessThis chapter discusses three topics that affect the deployment of SOAP servers. It discussessecurity, Enterprise Application Integration (EAI), and high-volume SOAP technologiesrequired to maintain a desired Quality of Service (QoS).

SECTION THREE: TESTING AND CAPACITY PLANNING

Once the building blocks of a J2EE application are built and connected, the application'sperformance must be tested and supported throughout its lifecycle. Strategies for scalabilityand performance testing are presented with Web Services used as an example. Once anapplication is deployed, capacity planning ensures that the application will meet itsperformance objectives as workloads and user numbers increase. Strategies and bestpractices for capacity planning are presented in this section.

Chapter 11 Testing Web ServicesThis chapter discusses a scalable framework for developing Web services, strategies foravoiding performance problems, and offers an open-source set of test objects and a scriptinglanguage called TestMaker that can help with performance and scalability testing.

Chapter 12 Capacity Planning for the WebLogic ServerThis chapter covers three issues that affect capacity planning. The issues are 1) How toperform analysis to determine what factors to consider for capacity planning, 2) How toderive a set of baseline metrics for capacity planning, and 3) capacity planning bestpractices.

Copyright © 2003 VERITAS Software Corporation. All Rights Reserved. VERITAS, VERITAS Software, the VERITAS logo, and all otherVERITAS product names and slogans are trademarks or registered trademarks of VERITAS Software Corporation in the US and/or othercountries. Other product names and/or slogans mentioned herein may be trademarks or registered trademarks of their respectivecompanies. Specifications and product offerings subject to change without notice.

Page 5: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

TABLE OF CONTENTS

Section One: Architecting and Analyzing J2EE™ Performance

Chapter 1: J2EE/EJB: A Case Study of an Industry-Standard Computing InfrastructureExcerpted from: Software Architecture in Practice, Second Edition by Len Bass, Paul Clements & Rick Kazman

Relationship to the Architecture Business CycleRequirements and QualitiesArchitectural SolutionSystem Deployment DecisionsSummaryFor Further ReadingDiscussion Questions

Chapter 2: Addressing PerformanceExcerpted from: Special Edition Using Enterprise JavaBeans™ 2.0 by Chuck Cavaness & Brian Keeton

The Role of Performance in DesignMinimizing Remote CallsOptimizing Entity Bean PersistenceBuilding a Pick ListManaging TransactionsTroubleshooting

Chapter 3: Common Bottleneck SymptomsExcerpted from: Performance Analysis for JAVA™ Web Sites by Stacy Joines, Ruth Willenborg, and Ken Hygh

UnderutilizationBursty UtilizationHigh CPU UtilizationUneven Cluster LoadingSummary

Section Two: Core J2EE™ Application Components

Chapter 4: ServletsExcerpted from: Java™ Performance and Scalability: Server-Side Programming Techniques, Volume 1 by Dov Bulka

Servlets Using PrintWriterServlets Using ServletOutputStreamPrecomputing Message BytesPumping More DataPingServlet—A Performance Upper BoundExtending PingServletSession StatePingJdbcCaching JDBC ConnectionsJSP—Java Server PagesRMIKey Points

Chapter 5: Advanced JSP and XML TechniquesExcerpted from: JSP™ and XML: Integrating XML and Web Services in Your JSP Application by Casey Kochmer and Erica Frandsen

Accessing Web Services from a BrowserHandling Large XML DocumentsHandling Special Characters and EncodingUsing XML Tag LibrariesSummary

Page 6: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

Chapter 6: Optimizing JavaStop PerformanceExcerpted from: e-Commerce Applications Using Oracle8i and Java from Scratch by Meghraj Thakkar

IntroductionTuning the Operating SystemCharacteristics of an Optimally Tuned Oracle SystemImproving JDBC Performance

Chapter 7: Session BeansExcerpted from: Developing Enterprise Java Applications with J2EE™ and UML by Khawar Zaman Ahmed & Cary E. Umrysh

Introduction to Enterprise JavaBeansEJB Views and the UMLSession BeansTypes of Session Beans and Conversational StateInstance PassivationTransactionsSession Bean TechnologyModeling Interface BehaviorSession Bean Life CycleSession Bean Common ScenariosModeling Session Bean RelationshipsManaging PerformanceThe Local ClientIdentifying Session Beans in Enterprise ApplicationsSummary

Chapter 8: Building Application Servers with Enterprise JavaBeansExcerpted from: Building Scalable and High-Performance Java™ Web Applications Using J2EE™ Technology by Greg Barish

The Need for Application ServersApplication Logic and Where to Deploy ItEnterprise JavaBeans: The J2EE SolutionHow EJBs WorkTypes of EJBSample ApplicationEJB DesignEJB ImplementationClient/EJB IntegrationScalability and Performance HintsSummary

Chapter 9: Business Tier Design ConsiderationsExcerpted from: Core J2EE™ Patterns: Best Practices and Design Strategies by Deepak Alur, John Crupi & Dan Malks

Business Tier Design ConsiderationsBusiness and Integration Tiers Bad Practices

Chapter 10: Using SOAP for e-BusinessExcerpted from: Building Web Services with Java: Making Sense of XML, SOAP, WSDL, and UDDI by Steve Graham, Simeon Simeonov,Toufic Boubez, Doug Davis, Glen Daniels, Yuichi Nakamura & Ryo Neyama

Web Services SecurityEnterprise Application IntegrationQuality of ServiceSummaryResources

Page 7: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

Section Three: Testing and Capacity Planning

Chapter 11: Testing Web ServicesExcerpted from: Java™ Web Services Unleashed by Robert Brunner, Frank Cohen, Francisco Curbera, Darren Govoni, Steven Haines,Matthias Kloppmann, Benoît Marchal, K. Scott Morrison, Arthur Ryman, Joseph Weber & Mark Wutka

Framework for Developing Web ServicesTest StrategiesTesting Web Services Using TestMakerNew Web Services Technology, New Test MethodologyScalability and Performance TestingBuilding Maintainable Test Agents with TestMakerScript Languages and Test AgentsMonitoring Web Services for Service Level GuaranteesResourcesSummary

Chapter 12: Capacity Planning for the WebLogic ServerExcerpted from: J2EE™ Applications and BEA™ WebLogic Server by Michael Girdley, Rob Woollen & Sandra L. Emerson

Analysis of Capacity PlanningMethodology and Metrics for Capacity PlanningCapacity Planning Best Practices

Page 8: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources
Page 9: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

Addressing Performance

C H A P T E R

2

Excerpted from: Special Edition Using Enterprise JavaBeans™ 2.0 by Chuck Cavaness & Brian Keeton

BUYBOOKHERE

Page 10: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources
Page 11: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

Addressing PerformanceIn this chapter

The Role of Performance in Design 464

Minimizing Remote Calls 465

Optimizing Entity Bean Persistence 468

Building a Pick List 473

Managing Transactions 476

17CHAPTER

Page 12: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

464 Chapter 17 Addressing Performance

The Role of Performance in DesignWorrying about performance when you’re first designing an application can be a stumblingblock if you’re not careful. Your first priority as a designer should be to produce a goodobject-oriented design. You want to build systems where responsibilities are allocated toreusable components that hide their implementations behind public interfaces. You wantthese components to provide a cohesive set of functionality while keeping the couplingbetween components to a minimum. You want each class that helps make up a component toencapsulate the data and methods needed for a related set of tasks and to do it in a way thatresults in granular classes that can be reused. And as if all that weren’t enough, you want yourclasses to be built from relatively short methods that are easy to understand, test, and extendas new requirements are added. This is a nice list of goals, but nowhere in it does it mentionperformance. The problem is that performance optimization and good object-oriented designdon’t always go hand in hand. They can instead contradict each other. Of course you can’tignore performance in your designs or you’ll face the risk of building a system that eithercan’t meet the constraints of its target environment or runs so slowly that no one will use it.The trick then is to know when to be concerned about how well a system will perform. Youdon’t want to minimize the importance of system responsiveness, but you don’t want to letanticipated performance problems that might never materialize drive a design either.

The nonfunctional requirements for an application should contain specifications that tell youas a designer what the criteria for a system’s performance are. This might include require-ments for the maximum time a user should be expected to wait for a Web page to display or the maximum time that can be allocated to a transaction that ties up an external system.Without requirements such as these, describing how well a system performs is subjective. This opens the door to systems that either don’t meet expectations or suffer from the oppositeextreme with designs that are too heavily influenced by concerns about execution speed. Whenyou know how a system needs to perform, it’s easier to determine if the performance require-ments pose a risk to building an acceptable application. The higher the risk, the earlier in theprocess it makes sense to worry about performance. The preferred approach from a strictlyobject-oriented point of view is to do a design, build the system (or pieces of it), isolate anyperformance problems, and then focus your efforts on alleviating the bottlenecks. If you’refaced with performance requirements that pose a risk, then it makes sense to prototype partsof the system to make sure the architecture can support what’s required. Otherwise, lettingperformance concerns creep into your design too early can lead to a less flexible system that’sdifficult to maintain and possibly not as portable to other platforms.

Performance optimizations made after a system has been implemented or partially proto-typed usually are application-specific. If specific queries are too slow, changes to the data-base schema or how the database is accessed might be necessary. If a problem is traced to a section of code that takes too long to execute, optimizations that might include rewritingsome of the code in a faster language can be pursued. It’s usually the case that overall per-formance is driven by a small percentage of the code. When this is true, you can expectgood results with this type of approach. When performance problems are more widespread,it’s possible that the architecture selected for the application is inadequate or it’s not being

Page 13: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

465Minimizing Remote Calls

fully exploited. It’s also possible for an architecture to be too heavyweight for a set ofrequirements. EJB offers a lot of benefits, but not every program needs the substance (andaccompanying overhead) of an enterprise-strength distributed architecture backing it.

Application-specific tuning is important, but, by definition, it’s specific to a particular systemand difficult to address in general terms. Basically, you have to first find out why an applicationdoesn’t perform as well as it needs to and then look for alternative approaches in the problemspots. There are, however, some general guidelines for designing better performing systemsfrom the ground up. You might think that this goes against what’s been said so far aboutdesigning for maintainability first and then tuning for performance only when necessary. Thatadvice is still true, but you also need to be conscious of the fact that building a system using adistributed architecture has known performance issues that have already been encountered andaddressed by many other developers. Addressing these issues with techniques that affect yourclass implementations without impacting your overall architecture offers you a way to avoidlater problems without sacrificing too much from a design standpoint. The intent of this chap-ter is to cover general performance guidelines consistent with this idea. Even if you don’t wantto address performance in your initial design, the topics covered here are a good place to startif you identify isolated problems after constructing an application.

Minimizing Remote CallsThe primary performance concern associated with a distributed architecture such as EJB is the amount of network traffic it requires. When a remote client makes a call to an EJBthere’s a certain amount of overhead involved. Part of this is just the time it takes to movedata between the client and the container across the network. You also have the impact ofthe transaction and security processing that takes place when the container receives a clientrequest. You can’t get away from this overhead completely because it’s part of the price youpay for the benefits of a distributed application. However, you should be conscious of thenumber of calls a remote client is required to make to do its work. As you’ve seen in earlierchapters, EJBs that are designed with remote clients in mind serve their purpose best whenthey’re coarse-grained. When an EJB is designed to provide significant business logic orworkflow management to a client, its overhead is easier to justify.

Even when an EJB is coarse-grained in terms of the functionality it provides, you still needto watch the number of calls you make to it. This point is easiest to illustrate with an entitybean that has quite a few attributes.

17

IIPart

Ch

As mentioned in previous chapters, entity beans are normally accessed through a localinterface. However, there might be circumstances where you need to expose an entitybean to remote clients instead. For example, if a session bean were deployed in a sep-arate JVM or on a different node in a cluster from an entity bean, it would need to usea remote interface to access that entity. A local interface can only be used for EJBsdeployed in the same JVM.

Page 14: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

466 Chapter 17 Addressing Performance

The EnglishAuctionRemote interface that was first introduced back in Chapter 6, “Bean-Managed Persistence,” exposes a number of get and set methods such as those shown in thefollowing subset of the interface:

...public void setName(String newName) throws RemoteException;public String getName() throws RemoteException;

public void setDescription(String newDescription) throws RemoteException;public String getDescription() throws RemoteException;

public void setStartingBid(Double newStartingBid)throws InvalidAuctionStatusException, RemoteException;

public Double getStartingBid() throws RemoteException;

public void setMinBidIncrement(Double newMinBidIncrement)throws InvalidAuctionStatusException, RemoteException;

public Double getMinBidIncrement() throws RemoteException;

public void setReserveAmount(Double newReserveAmount)throws InvalidAuctionStatusException, RemoteException;

public Double getReserveAmount() throws RemoteException;

public void setStartDateTime(Timestamp newStartDateTime)throws InvalidAuctionStatusException, RemoteException;

public Timestamp getStartDateTime() throws RemoteException;

public void setScheduledEndDateTime(Timestamp newScheduledEndDateTime)throws InvalidAuctionStatusException, RemoteException;

public Timestamp getScheduledEndDateTime() throws RemoteException;...

Methods such as these are no problem when declared in the EnglishAuction local interfacebecause the overhead of each call from a local client is relatively small. You can’t say thesame for using these methods in a remote interface, though. The problem with exposingfine-grained access to individual attributes like this is that a remote client that needs to reador modify multiple attributes has to make several calls on a bean’s remote interface to do itswork. You might not want to get rid of this fine-grained access because sometimes only asingle attribute needs to be accessed. What you want to do instead is provide alternative getand set methods that work with a data structure that holds multiple attributes of a bean. Ifyou can provide a client what it needs with fewer remote calls, the amount of time spentaccessing a bean is sure to drop. Listing 17.1 shows an example class that bundles multipleattributes of the auction entity bean together.

Listing 17.1 EnglishAuctionSnapshot.java—A Snapshot Data Object for an Auction Entity Beanpackage com.que.ejb20.auction.model;

/*** Title: EnglishAuctionSnapshot<p>* Description: Data object for an auction entity bean<p>*/import java.sql.Timestamp;

Page 15: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

467Minimizing Remote Calls

Listing 17.1 Continued

import java.io.Serializable;

public class EnglishAuctionSnapshot implements Serializable {public Integer id;public String name;public String description;public String status;public Double startingBid;public Double minBidIncrement;public Double reserveAmount;public Timestamp startDateTime;public Timestamp scheduledEndDateTime;public Timestamp actualEndDateTime;

}

The first thing to notice about EnglishAuctionSnapshot is that it looks more like a C/C++struct than a Java class. This simplicity in the declaration of the class is intentional. Theonly purpose of a class like this is to pass data. The absence of any methods (including getand set methods) makes it clear that there’s nothing to an EnglishAuctionSnapshot objectother than the data it holds. It’s referred to as a snapshot here because you can think of it as a snapshot view of an entity bean’s state at a particular instant. It’s of no value once the state of the entity changes. You’ll also see a class like this commonly referred to as a data object.

A snapshot class becomes useful when you add methods like the following to the remoteinterface (and implementation) of an entity bean:

public EnglishAuctionSnapshot getSnapshot() throws RemoteException;public void setFromSnapshot(EnglishAuctionSnapshot ss) throws RemoteException;

The idea is that a client that needs access to multiple attributes of an entity object can callits getSnapshot method instead of the individual get method for each attribute. An entitybean class implements this method simply by creating a new snapshot object and loading it with its current attribute values. The setFromSnapshot method is meant to provide theopposite capability by performing the equivalent of multiple set method calls with a singleremote call. You might have noticed that EnglishAuctionSnapshot was declared to imple-ment Serializable. This is necessary for a snapshot object to be used as a return value ormethod parameter in a remote interface.

The example shown here includes all the attributes of the associated entity bean in the snap-shot class, but it might also make sense to declare other snapshots that hold subsets ofattributes that are commonly used together. This should be a secondary concern to youthough. What’s more important is to go ahead and define at least one snapshot for an entitybean class. You’ll find in most cases that retrieving a snapshot with a reasonable number ofattributes is faster than making even two calls to individual get methods. Even if the snap-shot holds attributes that a particular client doesn’t need, the time spent building and pass-ing the complete structure can easily be made up by avoiding other remote calls.

17

IIPart

Ch

Page 16: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

468 Chapter 17 Addressing Performance

Optimizing Entity Bean PersistenceIf you’ve developed applications that work with relational databases, you know that databaseaccess can easily become the determining factor in how well a system performs. In a typicalbusiness application, the time spent executing your Java code is much smaller than the timetaken up reading from and writing to the database. With this in mind, any attention you payto performance while you’re designing a system needs to take the database into account. Inthe case of EJB, this, for the most part, means looking at your use of entity beans. Of coursefor some developers, this means avoiding entity beans altogether. That’s not the positiontaken here, but you do need to be careful when deciding if an entity bean is an appropriaterepresentation for a particular object. The accepted criteria for an entity bean’s use weredescribed back in Chapter 5. What this chapter is more concerned with is how to imple-ment an entity bean once you’ve made the decision to use one.

Choosing a CMP ImplementationIf you use CMP, the work the persistence framework does for you includes determiningwhen to write an entity’s state to the database and when to load it. The leading CMP imple-mentations compete with each other based on the features they provide to optimize theseparts of an entity object’s lifecycle. For example, an ORM framework such as TOPLink usedfor CMP can detect changes to an entity’s attributes and relationships and only write to thedatabase when necessary. When a database update is needed, the SQL statements that areexecuted are limited to the attributes and associations that have actually changed. An imple-mentation like this can also cache entity objects once they’ve been read to avoid unnecessaryreads from the database later. If you’re planning to deploy your application in a cluster, youhave to understand whether the caching provided by your CMP implementation supports aclustered environment to know whether you can take advantage of such a feature or not.

The EJB 2.0 Specification leaves nearly all the details of a CMP implementation up to theindividual vendors. Even though the mapping of an entity bean to a database can be donedeclaratively, taking advantage of any of the value-added performance features offered by aparticular implementation can result in programmatic dependencies on that product. The

Earlier examples made use of view classes to return a copy of an entity object’s state toits clients. The major difference between those classes and the concept of a snapshot isintent. View classes represent objects that are used to communicate with clients out-side the application tier. The auction example included the creation of view objects bythe auction entity bean, but views are often manipulated only by session beans. Asnapshot class exists solely for performance advantages when you’re supportingremote clients of your entity beans. Depending on your particular application, youmight be able to satisfy your need for a snapshot by reusing an existing view class.Otherwise, you can return a snapshot to a remote session bean and allow it, or ahelper class, to create a view based on the data in the snapshot.

Page 17: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

469Optimizing Entity Bean Persistence

concept of a Persistence Manager, which will provide more of a pluggable persistenceframework for CMP, has been deferred to a later version of the specification. For now, themost sophisticated CMP features tend to be nonportable. This doesn’t mean that you shouldignore what’s available to you—you just need to be aware of the implications.

Only Execute ejbStore when NecessaryChapter 6 covered the mechanics of how to implement an entity bean using BMP. Thatchapter showed you how to implement the various callback methods needed to keep anentity object in synch with its representation in the database. What that chapter didn’t dis-cuss in detail was how to improve the performance of a BMP entity bean.

The container calls an entity bean’s ejbStore method when it needs to make sure that thedatabase contents are in synch with the entity object in memory. This call is always made at the completion of a transaction that involves the entity. It also happens right before anentity is passivated. If you write to the database whenever a business method is called thatmodifies the entity, ejbStore isn’t responsible for much. However, the opposite is typicallytrue. Your business methods will usually update the state of an entity object but not writeany changes to the database. It’s in ejbStore that you most often execute the JDBC call (orcalls) needed to update an entity’s representation in the database. This simplifies your busi-ness method code and helps isolate your business logic from any knowledge of the persis-tence mechanism being used. The drawback to this approach is that a simple ejbStoremethod that blindly writes to the database even when an entity’s state hasn’t changed sincethe last update is inefficient.

Database access is an expensive operation in terms of performance. Because of this, it’s usu-ally worthwhile to perform a little extra processing within your entity beans to only updatethe data that has been modified since the last call to ejbStore. If you’re using an ORMproduct for your BMP implementation, this might be taken care of for you. Some frame-works can compare the current state of a persistent object with its state last retrieved fromthe database and only update the attributes that have changed. It takes some work, but youcan take a similar approach yourself and track changes to an object between ejbLoad andejbStore calls. Without an ORM framework to manage this for you, you might not wantthe complexity of tracking individual attributes, but you can easily keep up with whether ornot an entity object has changed at all. You can declare a transient boolean attribute that youset to true whenever a business method call results in a change to the persistent state of anentity object. This allows you to only perform the database updates in ejbStore when theindicator has been set. Both ejbStore and ejbLoad can reset the indicator to false beforereturning. The following fragment shows an example business method using this approach:

public void setName(String newName) {boolean change = false;if (name == null) {// a change if current value is null and the new one isn’tchange = (newName != null);

}else {

17

IIPart

Ch

Page 18: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

470 Chapter 17 Addressing Performance

// current value isn’t null, so use equals method to detect a changechange = (!name.equals(newName));

}if (change) {name = newName;modified = true;

}}

You could then modify this entity bean’s ejbStore method like the following:

public void ejbStore() {

// exit if the entity state hasn’t changedif (!modified) {return;

}

// obtain a database connection and update the database...

// entity state has been synchronized, so reset the indicatormodified = false;

}

Your individual business methods become slightly more complex when using this approach,but that’s the price you pay for a performance optimization. You can clean up the businessmethods by pulling out the logic needed to check for changes and implementing it in a setof simple helper methods. The extra processing that has to take place to detect and keep upwith changes is insignificant compared to the potential savings in database access time.

Use Lazy Loading for BMP Dependent ObjectsJust as paying attention to how you save data affects performance, so does the approach youuse for loading an entity object. In particular, it’s how you manage an entity’s dependentobjects when using BMP that can impact performance. As a general rule, you should waituntil data is actually needed from the database before you retrieve it. Using a lazy loadingapproach avoids database accesses for values that are never used by an application.

In Chapter 6, the ejbLoad method for the EnglishAuctionBean loaded the various attributesthat describe an auction but it only loaded the primary keys for the leading and winning biddependent objects and the assigned item entity. The corresponding bid and item objects forthese keys were not loaded. If you take this approach, you can maintain two references foreach object with which an entity has a one-to-one relationship: one for the primary key andone for the actual object. The implementation for ejbLoad only needs to be responsible forloading the primary key reference. When the related object is needed, the fact that the ref-erence to it is null and the primary key reference isn’t can be used to trigger a databaseaccess to retrieve the necessary data and instantiate the object. Listing 17.2 shows an example of this approach.

Page 19: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

471Optimizing Entity Bean Persistence

Listing 17.2 getLeadingBid—A Method for Loading a Dependent Object on Demandprotected Bid getLeadingBid() {

// see if the leading bid has been loadedif ((leadingBid == null) && (leadingBidId != null)) {leadingBid = loadBid(leadingBidId.intValue());if (leadingBidId.equals(winningBidId)) {// winning bid is the same as the leading bidwinningBid = leadingBid;

}}return leadingBid;

}

Listing 17.2 shows how to delay the loading of a dependent object until it’s needed. Noticethat the loadBid method is only called if the reference to the leadingBid is null and theleadingBidId isn’t. Listing 17.3 shows the loadBid method that pulls in the rest of the information for the bid object when it’s needed.

Listing 17.3 loadBid—A Method for Loading a Dependent Bid Object

private Bid loadBid(int bidId) {Connection con = null;PreparedStatement stmt = null;ResultSet rs = null;try {con = BMPHelper.getConnection(“auctionSource”);stmt = con.prepareStatement(“SELECT id, TransactionId, BidDateTime, “ +“Amount, BidderId from bid where id = ?”);

stmt.setInt(1, bidId);rs = stmt.executeQuery();if (rs.next()) {return createBid(rs);

}}catch (SQLException e) {// throw a system exception if a database access error occursthrow new EJBException(e);

}finally {// close the connectionBMPHelper.cleanup(stmt, con);

}return null;

}

As you can imagine, the code needed to do this can start to get out of hand if you have toimplement this type of functionality for more than a few dependent objects. To prevent thisproblem, you need a framework that manages the lazy loading of an object generically. Sucha framework needs to provide a class that encapsulates the details shown in Listing 17.2. Asyou can imagine, doing this in a generic form that can be reused for any dependent object

17

IIPart

Ch

Page 20: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

472 Chapter 17 Addressing Performance

class is not a simple task. You can do it, but before starting down the path of reinventing thewheel, you should consider using a third-party ORM framework that has already solved thesame problem for you.

Lazy loading is even more important for one-to-many relationships because you have toload more objects for each association. Rather than loading all of an auction’s bids inejbLoad, EnglishAuctionBean took a similar approach to what was done for the leading bid.In this case, nothing was read for the dependent bid objects in ejbLoad because the foreignkeys are in the bid table. Instead, all retrieval from this table is done when the list of bids isfirst accessed. The comments about using a framework approach apply even more so here.Managing a list of dependent objects is more complex because you don’t want to be ineffi-cient in writing updates to the database when elements have been added to or removed fromthe list. Specifically, a BMP framework for managing a list of dependent objects needs tosupport lazy loading of the elements, tracking of modified entries, the addition of entries,and the removal of entries. This is the only way to ensure that interaction with the databaseis kept to a minimum.

Using Read-Only Entity BeansThe EJB specification defines entity beans to represent read-write objects. This means thatregular calls to both ejbLoad and ejbStore are part of the normal management of an entityobject’s lifecycle. Sometimes, however, you might represent persistent data using an entitybean that’s never modified by the application. As described earlier in the “Optimizing EntityBean Persistence” section, you can avoid unnecessary database writes by only executing yourejbStore methods when necessary. This doesn’t, however, help you if you’re using CMP.

The EJB 2.0 Specification doesn’t require the container to support the concept of a read-only CMP entity bean. The idea of using read-only CMP entity beans is to avoid unneces-sary calls to ejbStore. Some vendors already offer a read-only entity bean as an option.Others are looking at taking this further by making it possible to bypass an ejbStore callwhen an entity bean’s attributes have been accessed (through its get methods) during atransaction but no other operations have been performed on it.

As an example, WebLogic allows you to designate an entity bean as read-only. It’s assumedthat data represented by this type of bean is being updated externally (or there wouldn’t beany reason for it to be stored in the database). To support detecting external changes to aread-only entity, you can specify how often the data should be updated from the database.

As it’s been defined so far, the example auction site is responsible for maintaining auctiondata but the items offered for auction could be defined by another system responsible formanaging a company’s inventory. This would allow the item entity bean to be implementedas read-only. Because this is a vendor-specific option, you have to declare this in theWebLogic deployment information as shown in the following:

<weblogic-ejb-jar>...<weblogic-enterprise-bean><ejb-name>Item</ejb-name>

Page 21: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

473Building a Pick List

<entity-descriptor><entity-cache><read-timeout-seconds>600</read-timeout-seconds><concurrency-strategy>ReadOnly</concurrency-strategy>

</entity-cache></entity-descriptor>

</weblogic-enterprise-bean>...

</weblogic-ejb-jar>

This deployment directive informs the WebLogic EJB container that ejbStore calls aren’tnecessary for the item entity bean. The read-timeout-seconds entry allows you to specifyhow often the data should be refreshed from the database. You can use a value of 0, which isthe default if the entry is omitted, to request that the entity only be read when it’s firstloaded into the entity cache. Using this deployment option is only valid if the applicationnever attempts to update an entity object of this type and the NotSupported transactionattribute is assigned to the entity’s methods.

Building a Pick ListA common requirement for a business application is to display a list of items from which auser makes a selection. This can be a list of customers or products in a catalog or anythingelse. The basic behavior is the same—the user views a list that contains some summaryattributes for each entry and then picks from the list. The system responds by displaying a more detailed view of the selection that includes additional attributes.

The potential performance problem with building a pick list is that reading all the attributesfor the items in the list is inefficient. It would be faster to only read the summary informa-tion that’s needed for the list and then read the detailed attributes for an entry only whenthey’re requested. If you’re using entity beans for all your data retrieval from the database,this can create a problem. For example, the findAllAuctions finder method declared inChapter 5 as part of the EnglishAuctionHome interface could be executed by a session beanmethod to build a list of auctions for the user to view. If you think back to how a findermethod works, you know that simply executing a finder doesn’t instantiate any entity objects.All an ejbFind method has to do is determine the primary key values that match the selec-tion criteria and return those. It’s not until a business method is executed on the component

17

IIPart

Ch

Some developers argue that an option like that just described violates the current EJBspecification because ejbStore isn’t called at the end of each transaction thatinvolves the entity. The response in a case like this is that the intent of the specificationis being upheld because all that really matters is that changes made to an entity objectare synchronized with the database. If an application never changes the object, no out-going synchronization is ever necessary. To eventually quiet the debate, EJB 2.0 listsread-only CMP entity beans as a desired feature that will be added in a later release ofthe specification.

Page 22: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

474 Chapter 17 Addressing Performance

interface corresponding to a particular object identity that an entity object has to be loadedand activated. The point here is that a finder method approach might be acceptable if youcan avoid business method calls on the entities that aren’t needed for display. Suppose youhave 1,000 auctions in the database but only 15 at a time need to be returned to the Webtier for display to the user. Using a finder method might be an acceptable approach if thefinder method query can be built to only return the 15 auctions that are needed. Or if thefiltering done by the application doesn’t involve any processing (sorting, for example) thatcauses a business method call to each entity. This latter case always has some additionaloverhead because 1,000 primary keys would have to be read and returned even if the entitiesassociated with the majority of them were never loaded.

If the overhead of loading and instantiating unneeded primary keys within a finder is toomuch or the logic that determines which elements go in a list requires attributes other thanthe primary key, you should consider another option. Instead of executing a finder method,you can implement a session bean method that accesses the database directly using JDBC(or an ORM framework query) and loads the attributes needed to build the pick list. In thiscase, the session bean method can execute whatever query is necessary to build the viewobjects used by the Web tier. When the user requests the details for an entry displayed inthe list, the primary key associated with that particular view object can be used to make afindByPrimaryKey call that loads the corresponding entity object.

Listing 17.4 shows a method that could be added to the implementation of theAuctionHouseBean session bean to retrieve the data needed to build a pick list of auctions.

Listing 17.4 getAllAuctions—A Method for Building a List of Views in a Session Bean/**

* Return entries for an auction pick list. The session bean performs* the necessary queries instead of accessing an entity bean finder method* in this case.** @param startIndex the element to start with (1-based)* @param numToReturn the number of auction views to return* @return a list of AuctionSummaryView objects sorted by name*/public List getAllAuctions(int startIndex, int numToReturn) {

Connection con = null;PreparedStatement stmt = null;ResultSet rs = null;List auctions = new ArrayList();try {con = BMPHelper.getConnection(“auctionSource”);// perform a query to select all the necessary attributesstmt = con.prepareStatement(“SELECT id, Name, Status, LeadingBidId, “ +“ScheduledEndDate FROM auction ORDER BY Name”);

rs = stmt.executeQuery();

// move to the right spot in the result setfor (int i=0; i<startIndex; i++) {if (!rs.next()) {

Page 23: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

475Building a Pick List

Listing 17.4 Continued

// not enough entries, return an empty listreturn auctions;

}}

// create views for the desired number of auctionsPreparedStatement bidStmt = con.prepareStatement(“SELECT Amount FROM bid where id = ?”);

for (int i=0; i<numToReturn; i++) {if (rs.next()) {// instantiate a view and set its attributesAuctionSummaryView view = new AuctionSummaryView();view.setId((Integer)rs.getObject(“id”));view.setName(rs.getString(“Name”));view.setStatus(rs.getString(“Status”));view.setScheduledEndDateTime(rs.getTimestamp(“ScheduledEndDate”));Integer leadingBidId = (Integer)rs.getObject(“LeadingBidId”);view.setLeadingBidAmount(null);if (leadingBidId != null ) {// load the leading bid to get the bid amountbidStmt.setInt(1, leadingBidId.intValue());ResultSet rsBid = bidStmt.executeQuery();if (rsBid.next()) {BigDecimal bd = rsBid.getBigDecimal(“Amount”);view.setLeadingBidAmount(new Double(bd.doubleValue()));

}}// add the view to the list to returnauctions.add(view);

}else {break;

}}bidStmt.close();

}catch (SQLException e) {// throw a system exception if a database access error occursthrow new EJBException(e);

}finally {// close the connectionBMPHelper.cleanup(stmt, con);

}

// return the viewsreturn auctions;

}

What’s important about the concept illustrated by Listing 17.4 is that choosing entity beansto manage your persistent data doesn’t rule out using more efficient access in certain cases.This is especially true when you need read-only access to your entity data. Unless you’redealing with entities that only result in a small number of instances, you should always

17

IIPart

Ch

Page 24: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

476 Chapter 17 Addressing Performance

consider using a session bean to build your lists of summary data. Entity beans provide veryhelpful functionality when you need to create and edit persistent data, but the associated over-head can quickly get in the way when all you need to do is read and report some information.

Managing TransactionsAs discussed in Chapter 12, “Transactions,” it’s expected that most EJBs you write will beinvolved in performing transactional work. This usually means that your EJBs will beaccessing and updating shared data in a relational database. The transactional support pro-vided by the EJB container does most of the work of managing transactions for you, butthere are a couple of points to keep in mind that can affect the performance of your applica-tions. You need to be sure that your transactions are being demarcated at the necessaryboundaries and that the resource locking that’s being enforced isn’t excessive.

Transaction DemarcationWhen you deploy an entity bean, you should usually specify a transaction attribute ofRequired for the bean’s business methods. You might have some special needs that make oneof the other attributes more appropriate, but those situations are rare. When you use theRequired attribute, all updates to an entity object take place within a transaction that can berolled back if necessary. You always need to define the transactional requirements for yourentity beans, but it’s usually redundant because they’re being accessed by session beans onbehalf of clients. If a session bean method is executed within the context of a transaction, the same transaction is associated with any entity bean methods it calls that have a transac-tion attribute of Required (or Supports). This is the way to package work done by a sessionbean method into an atomic unit of work.

Application behavior changes from what’s been described so far if a session bean method isexecuted without an associated transaction or it accesses entity bean methods deployed withthe RequiresNew attribute. In either of these scenarios, a new transaction is started and com-mitted every time an entity bean method is called. This creates a lot of overhead that is sureto slow an application. However, performance isn’t so much the driver of the point beingmade here, as it is the indicator of a problem. If a call to a session bean method results inmultiple transactions as entity bean methods are executed, the work being done cannot berolled back as a single unit if there’s a problem. If you’re suffering from performance prob-lems due to transactional overhead, you need to first be sure that your transaction bound-aries are being established correctly.

Isolation LevelChapter 12 introduced the read uncommitted, read committed, repeatable read, and serializ-able isolation levels that can be used to control concurrent access to resources. Using theserializable isolation level protects an application from erroneous results by preventing atransaction from accessing any data being manipulated by another in-progress transaction.This is an important trait for critical operations, but it does impact performance. The locking

Page 25: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources

477Troubleshooting

done to support this isolation level slows concurrent access to a resource so you should limitthis level of protection to the parts of your application that actually require it.

➔ For more information on isolation levels, see “Isolating Access to Resources,” p. 359.

TroubleshootingApplication Performs Poorly

My EJB application runs too slowly and I don’t know where to start in trying to speed it up.

Knowing what part of an application to focus on is key to improving its performance. Firstyou need to determine which operations are the slowest, which you can do simply by exe-cuting the methods exposed by your session beans. You can also get information on thisusing some of the tools described in the chapter that follows on stress testing. Once youhave a particular operation to focus on, it’s important to assess how much of its workload isactual processing and how much is database access. Once you know this, it’s easier to startproposing changes to how the operation is implemented. The main guideline to rememberin addressing performance is a simple one—be sure you know where the bottlenecks in asystem are before you implement any optimizations.

Page 26: KEY DEVELOPMENT & DEPLOYMENT …eval.veritas.com/mktginfo/downloads/Veritas_ch2.pdf · Best practices for balancing ... Monitoring Web Services for Service Level Guarantees Resources