Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Avoiding Performance Pitfalls with Entity EJBs

Avoiding Performance Pitfalls with Entity EJBs

Entity Enterprise JavaBeans (EJBs) are a convenient means to map persistent data to Java components. Container-Managed persistence (CMP) provides rapid development since the EJB container automatically handles loading and storing the persistent data. However, along with their many advantages, Entity EJBs can lead to very slow performance when used incorrectly. This column details a few common pitfalls which trip up EJB programmers and hinder the performance of their Entity beans.

Primary Key Classes
Like a database row, entity beans have an associated primary key. This primary key may be a single entity bean field. In this case, the entity bean can use the field's class as the primary key.

It's also possible to provide a custom primary key class. This is necessary for a compound primary key, one that maps to multiple entity bean fields.

With a custom primary key class, the developer must implement the hashCode and equals methods. Since the EJB container often uses the primary key class in its internal data structures, this class must implement hashCode and equals correctly and efficiently (see Listing 1).

Implementing hashCode
The hashCode method must return the same value for two objects which are equal, and it should attempt to distribute the hashCode values relatively evenly. Our first implementation, shown below, is efficient and correct, but it does not distribute the hashCode values at all. This hashCode implementation transforms any hash table into a list and forces linear searches. Clearly, this defeats the whole purpose of having an indexed data structure.

private int hash = -1;
public int hashCode() {
if (hash == -1) {
hash = str.hashCode() ^ i ^ b;
}
return hash;
}

The hashCode implementation above computes the Exclusive OR (XOR) of the string's hashCode and the primitive fields. XOR should be preferred to other logical operators such as AND or OR since it gives a better distribution of hash values. This implementation also caches the hashCode value in a member variable to avoid recomputing this value.

Implementing Equals
The equals method compares the current object with the passed parameter and returns true if the Objects have the same value. The default java.lang.Object.equals compares the reference (pointer) values and returns true if they are equal. For most primary key classes, this needs to be overridden to compare the values within the primary key class (see Listing 2).

The first line of the optimized equals implementation compares the passed reference against this. While this appears strange at first, it is a common case when the EJB container checks whether a primary key already exists in its data structures.

Next, we have replaced the getClass().equals with a much more efficient instance of check. The instance of operator returns true if the passed parameter's class is MyPk or one of its subclasses. Making the MyPk class final allows the create method to safely use the instance of operator since there cannot be a subclass.

Finally, the hashCode and member variables are compared. And expressions are short-circuited in Java which means that if the first expression is false, the second is not evaluated. Our equals method takes advantage of this by ordering the and statement with the cheapest comparisons first. The hashCodes are compared first since our implementation caches this value, and it should be very rare for both objects to have the same hashCode but not be equal. Next, the primitive fields are compared, and finally the more expensive java.lang.String.equals is called.

Loading and Storing Entity Beans
The WebLogic Server's EJB Container offers two distinct entity bean types: Read-Only entity beans and Read-Write entity beans. Read-Only entity beans support advanced clustered caching, and will be discussed them in another column.

Entity beans are transactional objects, and it is important to understand the relationship between transactions and persistence. When an entity bean instance is first used in the transaction, its state is refreshed from the database. Any modification to the entity bean state is flushed to the database immediately before the transaction commits (in the beforeCompletion callback, for those of you familiar with the javax.transaction.Synchronization interface).

Let's take a look at an example Employee entity bean that has the Required transaction attribute. You can assume that we created the bean in a separate transaction and currently have a reference to an Employee instance.

Employee e = ...
String name = e.getName();
e.setSalary(e.getSalary() * 2);
e.setLevel(e.getLevel() + 1);

The key observation from the code snippet above is that the caller has not started a transaction. Since the bean is deployed with the Required transaction attribute, each method runs as an individual transaction and causes loads and stores to the database. In this example, every getXXX method forces a database read while every setXXX method produces a database read and a database update. This simple example has five separate transactions with five database reads (SELECTs) and two updates.

Employee e = ...
tx.begin();
String name = e.getName();
e.setSalary(e.getSalary() * 2);
e.setLevel(e.getLevel() + 1);
tx.commit();

The code example above wraps the calls to the Employee entity bean within a single transaction. In this sample code we use a UserTransaction reference to manually begin and commit the transaction. This could also be done with a session bean with a container-managed transaction that then calls the entity beans within the container transaction.

When all of the business methods run within a single transaction, there are only two database accesses. The first getName call produces a SELECT statement to load from the database. The subsequent getXXX and setXXX methods do not cause any database access because they are within the same transaction, and the data is already loaded. When the transaction commits, an UPDATE statement is issued to write the new salary and new level to the database.

Using the Mandatory Transaction Attribute
Many EJB programmers deploy their beans with the Required transaction attribute. Required works in many cases because it inherits the caller's transaction if one exists and otherwise starts its own transaction. As we've seen earlier, developers must understand how transaction attributes can greatly affect performance. A new programmer on your team might be reusing the Employee entity bean and mistakenly call every getXXX method in an individual transaction. One way to prevent this is to deploy your entity bean with the Mandatory transaction attribute. Unlike Required, a Mandatory bean will not start its own transaction. If it is called with a transaction, the Mandatory bean participates in that transaction. If a Mandatory bean is called without a transaction, the EJB container immediately throws an Exception to the caller.

Deploying entity beans with the Mandatory transaction attribute is an easy way to indicate that the operations should be grouped together in a calling transaction.

The CMP Advantage -- Finders Loading Beans
Like business methods, entity bean finder performance depends on setting and using transactions appropriately. Let's consider another example with our Employee Bean.

Collection employees =
home.findEmployeesWithSalariesGreaterThan(30000);
Iterator it = employees.iterator();
while (it.hasNext()) {
Employee e = (Employee) it.next();
double salary = e.getSalary();
}

This simple example executes a finder (database query) to return employees whose salary is greater than the passed parameter, in this case 30,000. It then iterates through this collection and retrieves the salary from each. In the case where N employees are returned from the finder, this example does N+1 database hits. The finder hits the database and each of the subsequent getSalary call-backs hits the database.

By now, you've probably guessed that we'll try to execute the finder and the getSalary methods within a single transaction. Now, how many databases accesses will occur? The answers may surprise you.

If Employee is a CMP entity bean and the finder and subsequent getSalary methods occur in the same transaction, there can be one database access. The finder executes a select query which loads the associated primary keys and the other Employee fields. These prefetched beans are entered into the EJB cache and the getSalary method calls read directly from the memory cache. This is the finders-load-bean option in the weblogic-ejb-jar.xml. It is enabled by default, and it allows finders to prefetch additional data into the EJB cache. In this common case, it reduces the database access from N+1 to just 1.

What if the Employee is a BMP entity bean? It may surprise you, but there will still be N+1 database hits. The BMP entity bean will implement an ejbFindEmployeesWithSalariesGreaterThan method in the bean class to return a Collection of primary keys to the container, but it cannot prefetch into the cache. Each getSalary call then produces an ejbLoad call and another database hit.

Finders prefetching beans is a big performance advantage of CMP, and in general CMP (especially EJB 2.0's CMP) entity beans outperform BMP entity beans.

Conclusion
I hope these tips help you get the best performance out of your entity beans. We'll be looking at other performance tips and some of the new features in WebLogic Server 6.1 and EJB 2.0 in an upcoming column.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant th...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...