To EJB, or not to EJB?

Addressing the issues and decisions that go into adopting an EJB-based solution

To EJB, or not to EJB: that is the question.

Whether 'tis nobler in the mind, to suffer

The slings and arrows of outrageous licensing;

Or to take arms against a sea of potential overheads and features,

And by opposing end them? To roll your own: to reinvent the wheel;

No more; and by reinvent, to say, we continue

The heart-ache of low-level systems maintained in-house,

and the thousand natural shocks

That flesh is heir to; 'tis a consummation

Devoutly to be avoided.

(For Shakespeare's original "To be, or not to be," speech from Hamlet, see the sidebar.)

Once you have forgiven me for taking Hamlet apart with a chainsaw, you will realize that the lines above sum up the quandary every J2EE (Java 2 Platform, Enterprise Edition) architect faces: Are you over engineering your solution by employing EJB (Enterprise JavaBean) technology when the signs point to a different approach, indeed, perhaps a different technology? On the other hand, if you decide not to specify an EJB-based solution, have you subsequently found that a sizeable chunk of your code (that must be maintained) handles tasks best addressed by a container or a server?

This article shares with you how I methodically answer these questions.

Before I begin, let me set your expectations and explain my motivations for writing this article. First up, I do not answer the EJB/not EJB question for you, but I do provide a toolkit with which you can answer that question for yourself. Second, I have no hidden agendas: I do not represent an EJB server vendor, so I won't push EJBs for everything. On the other hand, I do not represent a technology or technique competing with EJB, apart from presenting it to you here as an alternative, so I won't deride an EJB solution where it makes sense.

Indeed, my motivation for this article stems from reader requests following my last JavaWorld article, "J2EE Project Dangers." In that article, I briefly touched on the danger of over-engineering, specifically around EJBs. Many readers requested a more in-depth treatise on the subject -- so here it is!

With that in mind, I propose to proceed as follows: In order to understand if you need EJB, you must understand an EJB solution's main advantages and disadvantages. As with all technologies, EJB has its weak points, and knowing these weak points is the first step to avoiding them. Following the discussion on EJB's weaknesses, I briefly outline alternatives to an EJB-based solution, both inside and outside the Java/J2EE world.

The final section is a proofing check. When you reach this part of the article, you should be comfortable applying the principles previously outlined to any business scenario. In that section, I present a progressive scenario that requires a solution (I promise not to pick either a pet store or an ATM machine!), make my call on the EJB/no EJB decision, and let you agree or disagree with my reasoning.

EJB advantages and disadvantages

Moving along, let's look at EJB's strong and weak points. In the disadvantages section, I also give solutions to commonly encountered EJB weaknesses.

EJB advantages

First, let's examine the advantages that the EJB architecture and programming model provides:

  1. The underpinning EJB specification: Funnily enough, EJB's main advantage -- its specification -- also represents its biggest disadvantage, as you'll see below. The specification stipulates everything for EJB, from the various types, lifecycles, and restrictions, right through to roles and responsibilities. Many vendors' application servers conform to the specification, allowing you to select a best-of-breed solution.

    EJB's universal nature offers application developers well-defined roles (I'll write the container and server, you write the business logic according to my APIs). Moreover, developers enjoy the certainty the spec delivers. Indeed, by choosing an EJB solution, developers benefit from a large skills pool, along with established best practices and open standards. Finally, found a show-stopper bug in your current server? If you have paid attention to portability issues in your design and implementation, with EJB you can circumvent it by moving to another vendor with minimum effort.

  2. Integration with the J2EE platform: Since Sun introduced EJB in 1997, a strong enterprise computing environment has grown up around it, including technologies such as servlets, JMS (Java Message Service), JSP (JavaServer Pages), the JCA (Java Connector Architecture), JDBC (Java Database Connectivity), security, and transaction management. Such integration enhances EJB's attractiveness as the J2EE platform includes so much other complementary technology.

    For you, the application architect or developer, you can rest easy because no matter how complex your application, the integrated, fully featured J2EE platform can handle your requirements.

  3. Almost transparent scalability: Because you delegate so much to the container, the vendor can scale server-side resources to meet fluctuations in demand. I say "almost transparent" because developers are somewhat affected. In the case of horizontal scaling and entity beans, for example, where application servers are clustered, you usually need to modify deployment descriptors to let individual server instances know they are not the only processes accessing and modifying a persistent store.
  4. Free access and usage of complex resources: When you buy a specification-compliant EJB server, you receive important features for free, namely transaction and security management, resource pooling, JNDI (Java Naming and Directory Interface), component lifecycle management, and more -- representing heaps of systems-level code you would otherwise have to design, build, and maintain in-house.
  5. A strong and vibrant industry and community: All the major IT players, with the exception of Microsoft, support EJB and J2EE, which means you are investing in a technology in which many other people have also invested. That investment commitment means the technology will be around for a long time. Additionally, enterprise Java technology continuously improves. For example, the EJB specification is currently at 2.0, having evolved from 1.0 and 1.1; a pattern likely to continue.

EJB disadvantages

Surprise, surprise, despite all the marketing hype over the past three years, adopting an EJB solution does present some disadvantages. Even more surprising, despite what you may have read over the past six months about these disadvantages, they are almost all avoidable when you know how:

  1. Large, complicated specification: In defense of Sun, no widely adopted distributed technology has avoided this pitfall; take a look at the CORBA specifications from the OMG (Object Management Group), or the architecture of Microsoft's .Net platform. Still, it would be good if there were a trail to follow in the specification for different roles. For example, EJB developers need only read Chapters 6 and 9 of the spec to understand session and entity beans. Additionally, in my experience two roles, not the six assumed in the spec, exist in practice: container/server providers and application providers, who build, assemble, deploy, and also administrate an EJB server. As such, the specification should reflect how EJBs are used in practice and how development teams are organized.
  2. Increased development time: I mention EJB development time in comparison to straight Java class development, not to other distributed environments. EJBs do take longer to develop, and when things go wrong, they can prove more difficult to debug, particularly because the bug might not be in your code but in the application server/container itself. Again, a difficult pitfall to avoid since the container gives you so much, but a disadvantage nonetheless.

    However, timely and targeted training can solve this problem. Knowing what the container/server should provide (by understanding the specification) and knowing how the container/server provides this (vendor documentation, sometimes augmented by training) will reduce EJB development time dramatically. On a technical note, an IDE that supports the Java Platform Debugger Architecture (JPDA) also proves invaluable in tracking down bugs.

  3. Added complexity compared to straight Java classes: At a superficial level, you require three classes for every session bean, four for an entity bean, and you may additionally employ value objects to reduce network overhead, adding another class. And I haven't counted the deployment descriptors yet, one that stores standard EJB information, the other with vendor-specific information!

    The solution: auto-generation. Tools like XDoclet reduce the amount of code you have to write, and it's free! Most IDEs feature auto-generation capabilities too, but they tie you to one vendor, and usually in a GUI-driven mode too, which means no automated builds or tests -- not a great solution.

  4. Potential to produce a more complex and costly solution than is necessary: The potential complexity and cost is a corollary of disadvantage number one concerning the complexity of the spec. Simply put, "If you don't get it, it will get you." That is, if you don't understand EJB, you won't take full advantage of it. Moreover, you will misuse parts of it and reinvent others, making your solution less maintainable and one that fails to capitalize on the advantages that make EJB a good idea in the first place.
  5. Continual specification revisions: No sooner have you deployed your shiny new EJB application than you see a new specification with newer features, rendering your application obsolete before it hits the streets. This situation, however, is unavoidable. As EJB technology matures, loose ends in earlier versions are tied up and new features added. Vendor release cycles contract in sympathy, and you need to move with them. Companies today upgrade application servers much more rapidly than they did databases three or four years ago, placing additional pressure on already tightened IT budgets.

Alternative approaches

So, if you are really uneasy about going down the EJB route, what alternatives exist? Well, assuming you want to stay with Java or employ another mainstream technology, then the answer is -- not many. I've listed below the main alternatives.

Avoid EJB completely, yet still employ a Java solution

Don't use EJB; simply write straight Java classes. This solution means you must explicitly handle (or ignore) issues such as multithreading, scalability, and transaction management yourself. Now if these issues don't affect your scenario, then there is no value in using EJB (or any comparable technology), so writing straight Java makes sense.

If, however, you must address those issues, and you still decide to forgo EJB, then you must write systems-level code as solutions. Such systems code usually starts out as a couple of base classes with utility methods like getConnection() and closeConnection(), plus a couple of XXXManagers, then quickly mushrooms into your own custom version of a stripped-down container that must be maintained in-house -- not a good solution.

Adopt an EJB-friendly design

As another alternative, you can plump for a solution that makes it easy to adopt EJB at a later stage. A number of widely available design patterns make this choice feasible; in fact "Designing Enterprise Applications with the J2EE Platform" uses many such patterns. More often than not, the adopted solution is usually a Model 2 architecture, with good separation between presentation (JSPs) and business logic (servlets), in preparation for a more robust and scalable middle tier in the future.

Move to a completely different technology

If you wonder whether Java technology is right for you, then take a look at CORBA or .Net. Other options exist, but these two represent by far the main competitors to EJB/J2EE.

Don't think about going to CORBA if you think EJB/J2EE is overkill for your needs, as CORBA is at least as comprehensive. In any event, the J2EE platform has supplanted CORBA as the premier open standards-based, cross-platform enterprise computing solution. All vendors who previously sold CORBA implementations now offer J2EE implementations.

Meanwhile, Microsoft has been pushing .Net heavily. .Net is language independent and platform dependent (EJB is language dependent and platform independent). By and large, the design and feature-sets of .Net and J2EE map very closely. At present, in my opinion .Net provides no competition to J2EE. It simply hasn't been around long enough, and the architecture's key features -- particularly the common language runtime (CLR) and C# -- are new and untested in production-class systems. However, make no mistake, .Net will be a strong competitor; Microsoft led the way with DCOM (Distributed Component Object Model) and ASP (Active Server Page) and will continue to add good ideas and technology to the enterprise computing space.

Think out of the box!

If none of the preceding options float your boat, then you may consider other candidate technologies such as Jini/JavaSpaces or Sandstorm, which are not widely used:

  • The Jini/JavaSpaces pairing has failed to attract any significant market share since its release, and is often found in an academic setting rather than in a commercial deployment. However, its simple model is easy to grasp, and it possesses the basic constructs required to build complex enterprise applications. I added Jini/JavaSpaces to this list because I am currently using it in an academic setting myself and appreciate its elegance. But I wouldn't use it in a commercial deployment as the backbone of my system just yet; I don't feel it has enough industry momentum or support. Your mileage may vary.
  • The exciting Sandstorm technology addresses the issue of scalability exclusively, but does not handle security or transaction management. However, it might fit some business scenarios. I would love to see an application server use Sandstorm under the hood!

The rule book

At this stage, I list a set of rules to guide you in deciding whether or not to use EJB. That's basically what the EJB/no EJB decision boils down to: looking at your own unique project and applying these rules.

Rules for choosing EJB

  1. Choose EJB when you know your application will need to scale beyond initial low usage levels and support multiple, concurrent users.
  2. Choose EJB if you need transaction management. For online catalogues or read-only systems with low user numbers, you probably don't need EJB. For financial systems or any system where you must preserve the ACID (atomicity, consistency, isolation, and durability) properties, EJBs are a must.
  3. Choose EJB if you need a comprehensive security model.

Rules for not choosing EJB

  1. Do not use EJB when you find no need for scalability, transaction management, or security and anticipate low numbers of read-only users.
  2. Don't choose EJB if you don't need platform independence and don't mind being locked into one particular vendor. This rule isn't designed to be sarcastic; intranet applications serve as a good example where I would like to see as little complication as possible. Indeed, a solution like .Net could prove highly successful in such situations, even in a beta release.
  3. Do not choose EJB if your team possesses no EJB experience (and you don't plan on ramping up or importing such experience).
  4. Do not use EJB just because your company got a free set of licenses from vendor X.
Figure 1. The main phases involved in deciding what technology to use. Note:

EJB folklore

Any technology that has grown as quickly as EJB has since 1997 is bound to spawn folklore. Some such myths were once true in an earlier version of the technology, many spring from unfamiliarity with EJBs, and some are promulgated by sources with hidden agendas. Below you'll find some example EJB folklore. Each example includes whether it's a myth, a half-myth, a misunderstanding, mostly true, or true:

  • You don't need developers to understand SQL if you are using container managed entity beans. Myth: Ridiculous, of course you do. Are you telling me that a serious enterprise would put mission-critical data in a database, and then let developers with no SQL knowledge write an application to access and modify that data ... and then take it live?
  • EJBs are portable between vendors. Half-myth: EJBs are portable if you write them to be. Session beans and BMP (bean managed persistence) entity beans usually port quite easily. In contrast, CMP (container managed persistence) entity beans need a good bit of work. Quite often, applications that rely on a clustering implementation take longer to port, as clustering is a big differentiator between vendors and is also not addressed adequately in the EJB specification. The work might not be in rewriting code, but in reconfiguring deployment descriptors and container/server configurations. In addition, administration and configuration tools and mechanisms are vendor-specific, as are things like startup and shutdown scripts and sometimes build scripts (unless the vendor uses the Ant build tool).
  • Security is free with EJB. Misunderstanding: The EJB specification provides a fully fledged security model (that integrates with the J2EE security model). But it is just a model, you need to set up your users and roles yourself -- and potentially tie in to an existing authentication source, such as a database or LDAP server.
  • EJB solutions are expensive. Mostly-true: The expense issue has long been a truth that should soon change to a myth. Open source and low-cost alternatives offer real competition to the entrenched market leaders. Additionally, I do not subscribe to the view that the cost of vendor licensing is usually a small fraction of a project's total cost. When you take into account per-CPU licensing and mandatory support contracts, the total cost of ownership is ridiculously high. Competition from within the J2EE industry and from without by Microsoft is good for pricing and feature development.
  • CMP is faster than BMP or BMP is faster than CMP. Misunderstanding: Whether one is faster than the other depends on the quality of the vendor's CMP engine and also on how proprietary it is. The more proprietary an application server is, the more features it can add to its CMP engine, like batch updates, smart updates, and more.
  • Entity beans are slow. True: Entity beans are often too slow and need to be worked around by a combination of session beans and value objects. This shortcoming is most noticeable in cases where a finder method returns thousands of rows. Invariably, you need to rework the business logic. In some cases, application servers try to be smart about loading data (lazy-loading), but such efforts often prove insufficient.
  • Stateful session beans are bad and should be avoided. Myth: Stateful session beans scratch an itch that stateless session beans cannot: maintaining server-side state across method invocations. As such, they are a required part of the EJB model and prove valuable in certain situations. However, they should be used sparingly as server-side state always adversely affects scalability. In general, I design all session beans to be stateless by default, but if it makes sense to convert a few to become stateful to meet business requirements, then that's fine.

Business scenario: Ice-Cold Beer Boutique

Well, I did promise not to use the pet store or an ATM example didn't I?! Instead, I picked a business scenario to show how to apply the knowledge built up over the previous sections -- the Ice-Cold Beer Boutique (ICB).

Month 0: The initial business requirements

I have been commissioned to recommend a technology solution to ICB -- a budding beer entrepreneur. The initial requirements include:

  • ICB plans to make its Website available to a select number of clients (less than 30) as a soft-launch. The site is a read-only catalog of premium beers available for shipment with no authentication or authorization required.
  • We are on a very tight hardware and software budget until increased business warrants further investment. Further, the existing team is not up to speed on EJBs, but does have good Java experience.
  • ICB plans to expand rapidly, adding read-write capabilities for authorized users, online purchasing by external clients, and plans to scale up to support 100 concurrent users in the medium term.

You will find a high-level overview of the proposed architecture and how it evolves as requirements change in Figure 2.

Figure 2. The evolution of the ICB architecture, from online catalog with no EJBs to a fully-fledged B2B architecture, using an EJB-centric model.

The correct solution

I cannot justify promoting an EJB-based solution at this stage. The business functionality requires none of the advantages EJB provides, and the load and concurrency requirements are not high enough at present to require EJB's scalability benefits. Further, the team lacks EJB experience, and there is no money or time for anything except basic training. However, these requirements will change if the business expands, so it would be foolish of me to build any design that mitigates against transitioning to EJBs in the future.

I recommend a JSP/servlet-centric approach for presentation and control with data access objects (DAOs) using JDBC for direct data access from the servlet layer and taglibs for direct SQL access from the JSP layer.

Month 3: The business expands

Business is good! The soft-launch was a complete success. Now ICB wants to expand. ICB wishes to take orders from 100 concurrent users, 2e hours a day, 7 days a week. Additionally, the company wants to accept online credit card reservations using a third-party provider.

The correct solution

We now have a number of compelling reasons to move to a fully fledged EJB-centric architecture. Three words to explain why:

  • Scalability: In three months, the core business requirement has increased 3.3 times in the number of concurrent users. This should act as a warning flag that if the business continues to expand, increases of this size will be the norm, not the exception.
  • Security: The servlet specification now provides access to a user's role and principal as well as authentication but does not provide per-method authorization -- the EJB specification does, and the current business scenario demands it.
  • Transactions: The J2EE 1.3 specification requires that servlets and JSPs be allowed to demarcate transactions using the javax.transaction.UserTransaction interface. However, the EJB specification provides much richer transaction management semantics (see the Enterprise JavaBeans 2.0 Specification, Chapter 17 for more details).

Month 12: ICB goes global!

In month 12, the business expands again. ICB has joined the Global Association of Beer Boutiques (GABB), and our solution must now support up to 300 concurrent users, as well as cohost and comarket WeissenBier from Germany and Abbey Beer from the Netherlands. Our new business partners use XML-RPC (XML over remote procedure call) to publish this information. They also provide access via a Java API to an Enterprise Resource Planning (ERP) system to track inventory changes and sales in realtime.

The correct solution

Now we can sit back and watch the benefits of EJB in action! A lot of work still must be done, but the core architecture to support a three-fold increase in concurrent users already exists. Because EJB servers can admit any Java code that meets the specification restrictions, not just EJBs, it also makes sense to deploy the ERP client library on to the application server and design an interface to expose the new API to existing code in a well-designed manner. Message driven beans (MDBs) and the JMS are obvious choices here. To support the increased number of concurrent users, we should employ both horizontal and vertical scaling, which will require testing to ensure the application behaves correctly in a clustered environment.

Knowledge is power

Any enterprise project can be built using EJB/J2EE. However, not all projects should be. As I began to write this article, EJB technology had just received a lot of bad press, particularly when one analyst released a research note warning against overspending on application server technology (see "Gartner: Don't Overspend on Application Server Tech").

The pro EJB group has had its day it seems, as EJB is now derided by almost everyone (too heavy, too slow, too expensive). This is short-sighted and premature: EJB technology makes complete sense for applications with high-end scalability and transaction-handling requirements. Prices are falling, JBoss (the only serious open source contender) continues to garner mind share and move into production sites, and major IT players such as HP are releasing free application servers. Microsoft is also fighting for our hearts and minds, which can only be good for the J2EE industry.

I hope that this article has laid to rest some of the folklore surrounding EJB and has shed some light on how to decide if EJB is right for you. As I've mentioned before, no substitute exists for hands-on experience; a critical part of choosing any technology is using it. Reading the specification is not enough, nor is surfing message boards or email lists (although they do help a lot, especially for vendor selection!). Design, build, and evaluate a thin slice of your application to see if it warrants an EJB approach before taking the plunge. Finally, good luck!

Humphrey Sheil, a Sun Certified Java Enterprise Architect, has worked on more than 25 enterprise Java projects in Europe and in the US, from initial scoping right through to live. Away from the office, he also researches the parallelization of neural network algorithms on compute clusters for bioinformatics applications at University College Dublin, Ireland.

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies