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 = ...
String name = e.getName();
e.setSalary(e.getSalary() * 2);
e.setLevel(e.getLevel() + 1);

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 =
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.

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
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix 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. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.