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

Related Topics: Weblogic

Weblogic: Article

Effective EJB: Make EJBs Work For You

"Java Development is at a Crossroads."

Do we façade? The decision to have a façade as a gateway for your other EJB components should be considered well ahead of time. It cannot be an afterthought. Once the decision has been made to have a façade, you can design the façade to return objects that are aggregations of values. The fine-grained access will be handled by the façade and is effective because it is generally within the container. This way we can reduce the number of round trips to the remote server.

Ok. We façade. But how good is our facade? When designing EJB interfaces the crucial points are that, for the purposes of designing remote interfaces, state should be avoided where possible and remote interfaces should be sufficiently coarse grained. Coarse graining interface design does not necessarily mean bundling all of the methods of your EJB layer inside one façade. Most often it is good to have multiple facades serving as gateways to your EJB components. When designing EJB-based architecture the safest approach is to find a balance between an object-oriented domain model and the procedural remote service layer.

Effective Exception Handling
Exception handling is another of the most muddled areas of EJB development. Exceptions are basically a breakaway from the expected behavior. These breaks are very common in distributed architectures because there are too many heterogeneous environments involved that are all connected by the network. A single network failure can trigger a catastrophe. Handling exceptions in EJB is particularly complex, and EJB involves two types of exceptions. The following are some guidelines for handling exceptions.

  • Refractor Logic out of Exception Handling Blocks. Having application logic inside exception handling code is a bad practice that often leads to code that is difficult to understand, change, and debug. The particular case in EJB programming where logic is deliberately pushed into exception handling code is transaction rollbacks. Rolling back transactions when there is an exception confuses program flow. Also, rolling back a container-managed transaction is not a straightforward task. EJB specification recommends use of EJBContext.setRollBackOnly() instead. Second, transaction rollback during an exception is not always appropriate. Third, transaction rollback falls outside of the transaction implementation. If an application throws an exception when running inside an EJB with notSupported transaction attribute, there is confusion as to whether to roll back the suspended enclosing transaction or not.
  • Don't Swallow Exceptions. Exception logging is an important part of any component design. One of the most common mistakes made by developers is to just print the exception and continue as if nothing has happened. Whenever there is an exception, it is an indication that something has gone wrong. The error could be on part of the container or in your application code itself. Simply logging exceptions without much detail makes debugging very difficult. Java provides an elegant way of logging the complete exception trace. In most cases, the exception trace would provide all of the information that is required to debug a problem. It is also better to have a custom verbose attached to the exception trace to help make understanding the situation easier.
  • Throw the Right Exception. Always. One bad practice in many EJB implementations is the tendency to wrap application exceptions into Container exceptions and throw them at the client. This practice stems from the misconception that the container handles all things for you when you are developing an EJB. However, container exceptions are specialized cases where there is a failure on part of the container, while the application exceptions are a run-time application failure. An example of application exception is invalid credit card number. This should not be wrapped inside a container exception like EJBException. The application exceptions are to be gracefully handled as in any other normal Java class.
  • Look for Hot Potatoes. A hot potato is a particular situation where a MDB repeatedly receives a same message and throws an exception while handling the message. When a JMS server does not receive an acknowledgement for a message delivered to a consumer, the server's only recourse is to resend the message. This sets the stage for repeated delivery of the same message indefinitely when the consumer that is processing the message does not handle an exception condition properly.
When developing MDBs care should be taken to identify potential areas of code that cause the hot potato situation. The solution for this is to break the acknowledgement and message processing into two execution paths. Acknowledge the message immediately once received. When an exception occurs during message processing, you may possibly write the exception to an error queue.

Effective EJB Persistence
The EJB specification addresses the persistence services through a special class of beans called entity beans. Entity beans are aimed at abstracting the domain data model. As such, they represent rows in a database table if the underlying datasource is an RDBMS. Initial specifications sparked a lot of controversy about entity beans and their usage. Henceforth, the persistence API has been rewritten twice in 1.1 and 2.0 specifications.

Because persistence is a fine-grained service it does not fit naturally into the coarse-grained nature of EJB services. This brings in a lot of confusion about how best to use entity beans. Before the decision to use entity beans has been made, a careful evaluation of alternate persistence models is advised. If a decision has been made to use entity beans, the following problems should be carefully considered and evaluated.

Exposing Entity Beans Directly to the Client Through Remote Interfaces
Due to their fine-grained nature, entity beans provide fertile grounds for antipatterns when exposed directly to the client. One of the most popular problems that is likely to be encountered is the n + 1 problem. This means you will require n + 1 remote calls to retrieve n attributes of a business entity. The extra call is to obtain the remote stub from the EJB container. Addressing the same retrieval function through a plain POJO DAO is much easier. All you will require is a JDBC call to retrieve the rows.

A more subtle problem associated with exposing entity beans is the loss of transaction integrity. Consider an entity bean with three mutator methods. Further assume that a client needs to update two columns of the entity represented by two mutator methods in a transaction. How does the client ensure that transaction integrity is maintained between two successive update methods on the entity bean? The only way out is to use a session façade to wrap the entity bean.

Avoid Application Joins
Managing entity relations within the application code will cause serious performance issues. Java is not optimized for database lookups. It is a bad programming practice to emulate application joins inside Java code. Databases use sophisticated technologies to optimize query access plans and consequently minimize the number of data comparisons. For example, the act of looking up for a Person entity when given an address entity within the application does not scale. These types of relations are best expressed in terms of a CMR field (from EJB 2.0). The number of comparisons that an application makes inside a loop construct in an attempt to simulate a relational join will have a severe impact on application performance.

More Stories By Shankar Itchapurapu

Shankar Itchapurapu is a software engineer at Oracle in India. He holds a Master's degree in Computer Applications. You can e-mail Shankar at [email protected]

Comments (3)

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.

IoT & Smart Cities Stories
Contextual Analytics of various threat data provides a deeper understanding of a given threat and enables identification of unknown threat vectors. In his session at @ThingsExpo, David Dufour, Head of Security Architecture, IoT, Webroot, Inc., discussed how through the use of Big Data analytics and deep data correlation across different threat types, it is possible to gain a better understanding of where, how and to what level of danger a malicious actor poses to an organization, and to determin...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.