Wednesday, November 21, 2012

CDI, when to break out the EJBs

I sometimes joke that CDI is basically EJB 4.0. While that's obviously not true there is a considerable amount of similarity and that does create a bit of confusion for people. Here is some general information on EJB and CDI as they relate to each together.


Note that EJBs are CDI beans and therefore have all the benefits of CDI. The reverse is not true (yet). So definitely don't get into the habit of thinking "EJB vs CDI" as that logic really translates to "EJB+CDI vs CDI", which is an odd equation.
In future versions of Java EE we'll be continuing to align them. What aligning means is allowing people to do what they already can do, just without the@Stateful@Stateless or @Singleton annotation at the top.

EJB and CDI in Implementation Terms

Ultimately, EJB and CDI share the same fundamental design of being proxied components. When you get a reference to an EJB or CDI bean, it isn't the real bean. Rather the object you are given is a fake (a proxy). When you invoke a method on this fake object, the call goes to the container who will send the call through interceptors, decorators, etc. as well as take care of any transaction or security checks. Once all that is done, the call finally goes to the real object and the result is passed back through the proxy to the caller.
The difference only comes in how the object to be invoked is resolved. By "resolved" we simply mean, where and how the container looks for the real instance to invoke.
In CDI the container looks in a "scope", which will basically be a hashmap that lives for a specific period of time (per request @RequestScoped, per HTTP Session @SessionScoped, per application @ApplicationScoped, JSF Conversation @ConversationScoped, or per your custom scope implementation).
In EJB the container looks also into a hashmap if the bean is of type @Stateful. An @Stateful bean can also use any of the above scope annotations causing it to live and die with all the other beans in the scope. In EJB @Stateful is essentially the "any scoped" bean. The @Stateless is basically an instance pool -- you get an instance from the pool for the duration of one invocation. The @Singleton is essentially @ApplicationScoped
So in a fundamental level, anything you can do with an "EJB" bean you should be able to do with a "CDI" bean. Under the covers it's awfully hard to tell them apart. All the plumbing is the same with the exception of how instances are resolved.
They aren't currently the same in terms of the services the container will offer when doing this proxying, but as I say we're working on it at the Java EE spec level.

Performance note

Disregard any "light" or "heavy" mental images you may have. That's all marketing. They have the same internal design for the most part. CDI instance resolution is perhaps a bit more complex because it is slightly more dynamic and contextual. EJB instance resolution is fairly static, dumb and simple by comparison.
I can tell you from an implementation perspective in TomEE, there's about zero performance difference between invoking an EJB vs invoking a CDI bean.

Default to POJOs, then CDI, then EJB

Of course don't use CDI or EJB when there is no benefit. Throw in CDI when you start to want injection, events, interceptors, decorators, lifecycle tracking and things like that. That's most the time.
Beyond those basics, there are a number of useful container services you only have the option to use if you make your CDI bean also an EJB by adding@Stateful@Stateless, or @Singleton on it.
Here's a short list of when I break out the EJBs.

Using JAX-WS

Exposing a JAX-WS @WebService. I'm lazy. When the @WebService is also an EJB, you don't have to list it and map it as a servlet in the web.xml file. That's work to me. Plus I get the option to use any of the other functionality mentioned below. So it's a no-brainer for me.
Available to @Stateless and @Singleton only.

Using JAX-RS

Exposing a JAX-RS resource via @Path. I'm still lazy. When the RESTful service is also an EJB, again you get automatic discovery and don't have to add it to a JAX-RS Application subclass or anything like that. Plus I can expose the exact same bean as an @WebService if I want to or use any of the great functionality mentioned below.
Available to @Stateless and @Singleton only.

Startup logic

Load on startup via @Startup. There is currently no equivalent to this in CDI. Somehow we missed adding something like an AfterStartup event in the container lifecycle. Had we done this, you simply could have had an @ApplicationScoped bean that listened for it and that would be effectively the same as an @Singleton with @Startup. It's on the list for CDI 1.1.
Available to @Singleton only.

Working in Parallel

@Asynchronous method invocation. Starting threads is a no-no in any server-side environment. Having too many threads is a serious performance killer. This annotation allows you to parallelize things you do using the container's thread pool. This is awesome.
Available to @Stateful@Stateless and @Singleton.

Scheduling work

@Schedule or ScheduleExpression is basically a cron or Quartz functionality. Also very awesome. Most containers just use Quartz under the covers for this. Most people don't know, however, that scheduling work in Java EE is transactional! If you update a database then schedule some work and one of them fails, both will automatically cleaned up. If the EntityManager persist call fails or there is a problem flushing, there is no need to un-schedule the work. Yay, transactions.
Available to @Stateless and @Singleton only.

Using EntityManagers in a JTA transaction

The above note on transactions of course requires you to use a JTA managed EntityManager. You can use them with plain "CDI", but without the container-managed transactions it can get really monotonous duplicating the UserTransaction commit/rollback logic.
Available to all Java EE components including CDI, JSF @ManagedBean@WebServlet@WebListener@WebFilter, etc. The@TransactionAttribute annotation, however, is available to @Stateful@Stateless and @Singleton only.

Keeping JTA managed EntityManager

The EXTENDED managed EntityManager allows you to keep an EntityManager open between JTA transactions and not lose the cached data. Good feature for the right time and place. Use responsibly :)
Available to @Stateful only.

Easy synchronization

When you need synchronization, the @Lock(READ) and @Lock(WRITE) annotations are pretty excellent. It allows you to get concurrent access management for free. Skip all the ReentrantReadWriteLock plumbing. In the same bucket is @AccessTimeout, which allows you to say how long a thread should wait to get access to the bean instance before giving up.
Available to @Singleton beans only.


DaveL said...

Nice post. It seems to me that there is no compelling reason to use CDI if you use a stateless server architecture. Is this true? I use EJB + GWT RPC services and I don't see what value CDI would add.

David Blevins said...

There are definitely some cool parts in CDI. The stuff I like tends to be the parts people don't talk about much.

I absolutely love CDI Events. I probably overuse them, but really it's cool.

Simply put, "listeners" are an obvious good way to decouple code, so nothing new there. The neat twist is that you can skip all the plumbing entirely.

In terms of state, @RequestScoped can eliminate the need for any kind of ThreadLocal usage you might have had. Some more plumbing gone.

I should maybe do a post on it.

chpressler said...

i am still confused who actually does the injection. CDI or EJB Container?
When CDI is not enabled then the EJB Container will do the Injection for all @Resource, @EJB, etc.
When CDI is enabled will the CDI Container do that injection for EJB's or is still the EJB Container responsible for injecting EJB's (EJB Container understands the @Inject Annotation)?
Also the @EJB is recognized by JSF for DI in ManagedBeans, but in POJOS controlled by the CDI Container. (it will only work with @Inject in POJOs).
Is there a best practice which Annotation should be used? Would you reccomend to only use the @Inject when CDI is enabled and abandon the @EJB and @ManagedProperty Annotations?

Unknown said...

Thanks for this great post, David!

One point comes to mind: you never mention remote invocation of EJBs.

I am very interested on your opinion on this... Do you think that is not relevant anymore? That nobody uses it? Do you think that nobody should use remote EJBs anymore?

All the best,


Alexandre Héroux said...

EJB can be deployed on another server and be invoke with IIOP/CORBA. That feature allows processing to be dispatch between specialized servers. CDI reside only on your presentation server and can't be split.

BnB said...
This comment has been removed by the author.
BnB said...

Hi David,
Thank you for this post, We use CDI+JAX-RS+EJB 3 running on Websphere 8. A @Stateful is injected into JAX-RS at class level, How do i get the stateful across jax-rs calls in a single httpsession ? right now I put this @Stateful bean into HttpSession manually, is there a way we can achieve this by CDI ?

Patrik Varga said...

Very important yet unclear topic covered in a very concise summary. Great post, congrats David.

@BnB, have you tried simply annotating your stateful bean with @SessionScoped, in addition to @Stateful, and then injecting/using it wherever you want?

John said...

I think this was very helpful, understandable, and illuminating. I'm encouraged to ask this question here.

If I inject a managed bean into an EJB, the same instance of the managed bean is used in every call to method on the ejb.

class MyEjb {
@Inject MyCdiBean myCdiBean;
public void someMethod() {
// touches myCdiBean, always the same instance.

I'm wondering where the jee or cdi specification is detailing this behavior, and whether these specify a way to use a different instance of my CdiBean on every call to someMethod. Using @RequiredScope did not work.


Christian Schlichtherle said...

Maybe you should add message driven beans to the list. AFAIK you can't set a message listener within an enterprise app, so you have to use message driven beans.

Martin Andersson said...

Thank you for your commitment to the Java community and this excellent blog post! However, please revise your first statement: "EJBs are CDI beans". It is wrong and causes confusion. See commentary of

André said...

"In terms of state, @RequestScoped can eliminate the need for any kind of ThreadLocal usage you might have had. Some more plumbing gone.
I should maybe do a post on it."

Please, do it! :)

David Blevins said...

I'm not sure I see where in Arjan's post the "EJBs are CDI beans" statement conflicts.

I can tell you from an EJB spec perspective we made the deliberate decision from the start of CDI to require that EJB implementations must support 100% of the CDI feature set on EJBs. Every aspect of CDI works on EJBs with the exception of scopes which we had to limit to @Stateful beans only.

Jean-Pierre Cuvelliez said...

Thank you for this post.

markmueller0815 said...

One thing to keep in mind though: EJB exception handling is very different from CDI. So you can not simply exchange a CDI for an EJB to get access to some EJB features.

Richard Evans said...

CDI interceptors, altnernative, etc - been reading about them, seem really useful.

But if I want to switch between alternatives based on some runtime configuration - system property, etc, how do I do that?

All the docs I have read descrbibe configuring these in beans.xml which is static once my app is deployed.

Akarsh Cholapurath said...

1 2 3 4 5 6

rahul pandey said...

fathers day quotes poems fathers day quotes for brother fathers day quotes for brother short fathers day poems funny fathers day photos fathers day images photos fathers day message to husband fathers day message to husband fathers day poems in spanish fathers day poems from son pictures of happy fathers day
poem on father's day happy fathers day brother images happy fathers day brother images fathers day poems for kids photos of happy fathers day funny fathers day photos happy fathers day message to my husband happy fathers day message to my husband cute fathers day poems fathers day wishes funny fathers day pictures

Admin RH said...

Munna Michael Full Movie

爸爸 x said...

20170619 junda
oakley sunglasses sale
cheap jerseys wholesale
burberry outlet sale
cheap ray ban sunglasses
adidas uk store
michael kors outlet clearance
cheap nba jerseys
true religion outlet
ray ban sunglasses
nike air max 90

Sana Shaikh said...

thanks for sharing !!!
pro kabaddi
pkl Kabaddi 2017 Schedule
pkl 2017 Schedule
prokabaddi live
pkl Schedule 2017
pkl Season 5 Schedule
pro kabaddi schedule

Sana Shaikh said...

nice post

Sana Shaikh said...

wonderful post!!

universal web said...

Happy Independence Day Greetings 2017
Quotes For Canada Day 2017
Pakistan Independence Day Wallpapers 2017
Happy India Independence Day Quotes

Abhilash appu said...

kerala lottery results today
today kerala lottery result

kerala state lottery
kerala lotteries results

wonderful post!!

lookandlike said...

meme good night
goodnight meme for him
good morning beautiful gif
good morning funny meme
good night sweet dreams quotes in hindi

arjun said...

Dma jharkhand recruitment

cg vyapam rheo recruitment

buat recruitment

telangana fisheries recruitment

Kurukshetra university recruitment

lascells said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point. |

frivtn100 said...

I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again
jogos friv 2
juegos kizi 8
juegos yepi 2
friv 5
juegos y8
juegos 5

universal web said...

This is what i was looking for thak you for sharing this amazing post. keep on posting these kind of nice post
avast premier license file
independence day wishes

hema kale said...

happy friendship day images
happy friendship day 2017
friendship day quotes
happy friendship day quotes
friendship images with quotes
friendship day messages
friendship day wishes
happy friendship day message
friendship day status
friendship day date
happy friendship day date
happy friendship day images

hema kale said...

An extraordinary thought to praise friendship in an inventive way is make a blurb on Friendship Day this year.
friendship day 2017
friendship images
friendship day pic
friendship day pics
friendship day photos
For some the best sort of Friendship Day festivity is maybe a heart-to-heart converse with a best friend Sharing everything that has made a difference to you and your frinds for so......
friendship day wallpapers
photos of friendship
friendship quotes images

friendship images hd
true friendship images

yogareddy is said...

The most unique way to celebrate Friendship Day would be hold a gathering for your favorate images,quotes,hd wallpapers,messages,pics,photos and many more... Be that as it may, this thought needs a touch of arranging and exertion as you have to choose where to post(facebook,whatssapp,twitter,instagrame etc..) Once that is done, ring your pals and simply have your indulgence !

happy friendship day images

happy friendship day 2017

friendship day quotes

yogareddy is said...

happy friendship day quotes

friendship images with quotes

friendship day messages

friendship day wishes

happy friendship day message

friendship day status
friendship day date

happy friendship day date

happy friendship day images

An extraordinary thought to praise friendship in an inventive way is make a blurb on Friendship Day this year.

friendship day 2017

friendship images

friendship day pic

friendship day pics

friendship day photos
For some the best sort of Friendship Day festivity is maybe a heart-to-heart converse with a best friend Sharing everything that has made a difference to you and your frinds for so......

friendship day wallpapers

photos of friendship

friendship quotes images

friendship images hd

true friendship images

luu quoc trung said...

To make yourselves available FNAF Friv Friv Games Thank you both for sharing Holy Mass with us each day Friv Games Twizl Juegos De FNAF when we were called out late at night and any other time and for your support and encouragement in every respect. Friv 2021 Twizl Juegos Yepi Juegos Twizl Thank you for sharing with me a few of your ideas regarding the possibility.

ngoem199 said...

Danke, dafur dass Ihr jeden Tag mit uns die Hl. Messe gefeiert habt, fur all die Reparaturen im ganzen Haus Jeux De Friv Jogos Friv Jogos Friv fur Euere Bereitschaft Juegos Friv Juegos Friv Juegos De Friv immer zur Verfugung zu stehen Juegos Geometry Dash Juegos Twizl Twizy Twizl Danke, dass Sie Ihr Muhen um den Aufbau des Leibes Christi mit uns teilten.

ngoem199 said...

A todos que partilham e trabalham sob estas mesmas convicções e princípios Friv Friv 360 Friv4school 2020 Senhor Deputado Cashman, agradeço-lhe a informação. Jeux De Friv 2018 Juegos De Roblox Juegos De Zoxy Mais uma vez, obrigada ao Parlamento por comungar da visão que informa a nova política dos consumidores Juegos Kizi 2017 Juegos Yepi 2017 Twizl 3 Zoxy 2 assente no mercado - a visão de um mercado de consumidores informados e capacitados que procuram e usufruem, com confiança,

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Recuritment & Notification 2017-2018 by following below given links...

fci andhra pradesh watchman recuritment 2017

fci tamilnadu watchman recuritment 2017

xat notification 2018

jkbote polytechnic result 2017

priyanshu beautique said...

You can go for a change from the conventional salwar suits to various gorgeous designer kurti. Designer kurtis are emerging with fashion and style which not only gives you a different flavour but also adds to your wardrobe and beauty.for more..
Plz visit:- Kurti
The designer kurtis are certainly the most mesmerizing creation of the Indian designers. These are basically the modified version of the traditional ladies kameez.for more..
Plz visit:- Designer Kurti

ngoem199 said...

Wir danken Ihnen Friv4school 2018 Gry Friv 2 Gry Friv 5 dass Sie diese Hoffnung mit uns teilen und diesen Schritt auf dem Pilgerweg des Vertrauens Gry Friv Juegos Friv 100 Juegos Friv 1000 mit uns gegangen sind. Juegos Friv 5 Juegos De Friv 2 Juegos Friv 250 Juegos Yepi wir danken Ihnen für das Interesse an unseren Produkten und hoffe

sarvesh singh said...

Happy labor day wishes quotes images sayings greetings one liner messages texts sms
Happy labor day 2017 USA weekend wishes, Latest quotes slogans for facebook whatsapp KiK
Happy Columbus day 2017 wishes Quotes images slogans sayings giphy messages, Columbus day sale
Happy Veterans Day 2017 Parade, wishes images slogans dishes quotes messages
Happy thanksgiving day 2017 wishes images quotes wallpapers messages sayings greetings slogans for whatsapp and facebook
Happy yom kippur 2017 traditions customs wishes images quotes greetings prayers slogans poems

friv 10 said...

Gracias por compartir sus ideas con nosotros. Friv Games Gry Friv gracias por la detallada información. Juegos Friv Gry Friv Friv Gracias por vuestras reacciones a las transmisiones que os han hecho. Friv Games Juegos Friv Acogemos con agrado los comentarios de los lectores.

William Smith said...

What Are The Advantages Of Cooking Pizza In Traditional Style?
Pizza Cooking Equipment
Labor Day
Wood Fired Pizza Oven
Platinum Series Wood Fired Pizza

William Smith said...

Diagnostic Imaging Parts Company

fieldtested dental equipment parts
What company is the best medical equipment supplier?
fieldtested dental equipment parts

William Smith said...

furniture store in CA
home office furniture San Jose
interior design ideas
gun sofa collection
quality furniture store