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.

EJB >= CDI

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.

654 comments:

«Oldest   ‹Older   601 – 654 of 654
heena said...

https://www.atranspackers.in/index.html

technology said...

these are also used for building customer loyalty, which is an important part of any business's success. Customer loyalty means that a buyer will continue to buy your product even if you raise the prices or make some changes. This is because these customers will trust your brand over others. For any business, it is extremely important to have some loyal customers. Salesforce interview questions

onlinepsychologicalcounselling said...

Alcohol Counsellor can help you with appropriate medical treatment, which can be tailored according to individual patients after careful assessment to improve the chances of success.

Friendship Counselling
Alcohol Counsellor
Counselling For Children
Autism Counselling

Tutorials said...

Very Informative and interesting blog!  Primavera course online  Best primavera p6 training online  

GPS Contact Number said...

Get the latest Rand McNally Lifetime Map Update from the experts of GPS Contact Number. Just dial our 24*7 toll-free number to get latest update or visit our website to know more!

Dubai Fun Club said...

Appreciated for taking time to write this nice article for letting know us this information.
Escorts in Dubai

loveyou said...

I have been looking for this information for quite some times. Will look around your website .
Goa Escort Service
Hyderabad Escort service
Call Girls in Delhi
Jaipur Escort Service

How to Fixr said...

Thank you for another informative site. Where else could I get that kind of info written in such an ideal method?
Roku Error
Roku Error Code
Brother Printer Error
Canon Printer Error

kepala bergetar said...

Kepala Bergetar drama online tonton Kepala Bergetar Tonton Online Malay Tv Dramas 2021 videos Live Streaming free, Kepala Bergetar Download terkini Live episods full hd dailymotion and youtube videos.

kepala bergetar

Hot Nikita said...

When men look for female escorts in Mumbai, they come across our escort agency Hot Nikita. For anyone who wants to have great nights, they can come to Hot Nikita.
Mumbai escorts
call girls in Mumbai

Best Body Massage In Bangalore said...

Stress could be harmful for most people. When this situation is not treated well, it can cause many other health issues in the future. Too much stress can affect your physical and mental health very badly
body to body spa near me
massage spa near me
massage near me

bhavik said...

Garlic Bulb Cutting Machine
Garlic Peeling Machine
Groundnuts Thresher Machine
Removing Machine
Silage Machine
Peanut Peeling Machine

meena r said...
This comment has been removed by the author.
meena r said...
This comment has been removed by the author.
meena r said...

Massage spa near me Search Below Best Total System Therapeutic Massage Centres in Bangalore. Body to Body Spa Bangalore supplying hot sort spa remedy. It assists the people to alleviate the strain and pain away from the whole human anatomy. There exists a lot of human anatomy massage centres in Bangalore.
massage parlour near me

meena123 said...

I am Sonali from Bangalore. I just shifted from Mumbai to work in massage spa center in Bangalore. If you are a man then getting massage from a girl can really help you in the release of some Harmons which are good for your health. Sandwich massage which is also known as 4 hand massage is performed by two girls to leave you energized after session. Imagine two beautiful girls giving you the best pleasure you have experienced in the life.

visit my website: massage spa near me

Talal khan said...

Amid speculation over contestants for Bigg Boss 15 being finalised, a source
from the Colors Tv channel is launching soon bigg boss 15 watch online live.

Bigg Boss 15 Watch Online

BtreeSystem Training said...

Btreesystem is Software IT Training Institute in Chennai
btree systems

Dr.Shah Clinic said...

Dr. Shah is Consultant Andrologist and Sexologist in Chennai
Sexologist in chennai
Sexologist doctor in chennai
Andrologist in chennai

Diya Jindal said...

Air Hostess Escort Mumbai
College Girls Escort Mumbai
High Class Escort Mumbai
Housewife Escort Mumbai
Russian Girls Escort Mumbai
Indian Escort Mumbai

Technogeekscs said...

Fantastic blog! Thanks for sharing a very interesting post, I appreciate to blogger for an amazing post.
Data Science Course in Pune
Python Classes in Pune

independentmumbaiescorts said...

Mumbai Escort Service offering hot greater Mumbai escorts. for meet me VIP escorts in Mumbai, online call girls in Mumbai and independent call girls Mumbai.
Mumbai Escort |
Mumbai Call Girls |
Andheri Escort |
Bandra Escort

bhavik said...

Precision Machining Works
CNC Machining Works
VMC Machined Parts
Industrial Valves

Chicks in Dubai said...

Connect for beautiful and hot girls entertaining services
Dubai Escorts
call girls in Dubai

heena sharma said...

Inside this massage, the many of these believe their human anatomy pain becomes paid down after some minutes of commencing this particular massage. As it can also be a kind of entire human body massage by the close of the session you may think the entire body gets relaxation.
massage spa near me
body to body massage near me
female to male spa near me
body to body spa near me
spa near me

jessy sharma said...

They truly are so amazing you simply won't quit staring in their own faces. Besides a face, they've got a fearless attitude which is rather scarce to discover in India.
escorts in goa

aishu said...

I read your article it is very interesting and every concept is very clear, thank you so much for sharing. AWS Certification Course in Chennai

Fubotv Activate said...

FuboTv allows its subscribers to live to stream their favorite TV networks. When you get access to fuboTv connect, you get access to view more than 150 channels, and it has everything you require in any streaming services, starting from the DVR capabilities to all kinds of high resolution streaming sports events. fubo.tv/Connect

Priya Escorts said...

Thanks for sharing this is very informative blog.
Mumbai Escorts

Patna Escorts

Chennai Escorts

Jaipur Escorts

Raipur Escorts

Noida Escorts

Ranchi Escorts

bhavik said...

Automático de líquidos Vial Llenado Con goma tapar la máquina
Automático de líquidos Vial Llenado Con Tipo de vacío de goma tapar la máquina
Automática sola cabeza líquido Vial de llenado, tapar y tapado de la máquina, (monobloque)


Máquinas de llenado de botellas

Volumétrica automática Botella Liquid Filling Machine
Automatic Liquid Llenado automático de líquidos Botella Y la máquina que capsula (monobloque)

Bepanah Pyar Full Episodes said...


Watch the Best and Interesting Drama Serial of Melayu Tv Channal Astro Citra,Astro Prima and Astro Ria.
Free Download the New Episod of Dramas and Movies in HD Quality.


Tonton Tv3 Dramas

Melayu Dramas Watch Online

yanmaneee said...

kyrie shoes
golden goose
lebron shoes
yeezy boost 350 v2
lebron james shoes
yeezy 500
yeezy boost 350
curry shoes
curry shoes
moncler jackets

sweetheart said...

Hi I am Arpita Jain. I am a Mumbai based escort girl. I offer personal services and so do my group of girls. There are many model Escorts working for me. If you are looking specifically for young girls, I have many College Escorts
Mumbai Call Girls
Juhu Escorts Service
Andheri Escorts
Bandra Escorts Service
Navi Mumbai Escorts
Mumbai Hotel Sex
Russian Escorts In Mumbai
Bombay Call Girls

Twinkle said...

Nice post. It is really interesting. Thanks for sharing the post!
Web Design Company in
Tuticorin
| Domain Name Registration In India
Web Design Company In India | Digital Marketing Company in India
PPC Services in India | SEO Company
India

Bulk SMS Service in India | Social Media Marketing Company in India

Sonika Das said...

Your article is fascinating. , you have enriched your craft delightfully. It rouses individuals a ton. In the event that the subject is acceptable, at that point it is likewise enjoyable to peruse and this is the thing that individuals need these days, your post is truly intriguing. Enlivened by you, I also figure I ought to compose an article on a great subject.
Escorts Service In Sector 57
Escorts Service In Haryana
Escorts Service In DLF Phase 1
Escorts Service in Sector 15
Sector 46 Escorts
bilaspur independent escorts
call girls in gurugram
escorts service in sector 40
call girls in gurugram
Colorful call girls

Abu Dhabi Escorts said...

Abu Dhabi Call Girls


Abu Dhabi Indian Escorts

naikin sign said...

thank you for the information provided, we are waiting for the next info at cara menggugurkan kandungan

Unknown said...

PG‌SUPER‌SLOT‌‌SUPER‌SLOT1234‌PG‌ ‌SLOT‌PG‌SLOT‌PGบาคาร่าสล็อต ฟรี

Ishq Par Zor Nahin Watch Online said...

Watch Ishq Par Zor Nahin All Episodes in HD Quality Streaming. Watch
Ishq Par Zor Nahin Video Episode Online. Today Ishq Par Zor Nahin Full Episode on ...



Ishq Par Zor Nahin Watch Online

Rupali sen said...

You are an excellent blogger...I have writen blogs on

Noida escort service
Delhi escort service

Rupali sen said...

I really like this post Please visit mine by clicking the link
Call girls in Jammu

Home Improvement said...

Great post I must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more. Quick analysis tool excel

Hotelescortservices.com said...

Get the best Delhi Escort service by independent Delhi escorts or Delhi call girls. Book call girls in Delhi or escorts in Delhi online visit http://www.mayaescortservice.com/

Jaipur Escorts Girls said...

Jaipur Escorts
Jaipur Call Girls
Jaipur Call Girls Service
Call Girls in Jaipur
Vip Call Girls in Jaipur
Independent VIP Escorts in Jaipur
Cheap Call Girls in Jaipur
High Profile Call Girls in Jaipur
Russian Call Girls in Jaipur
Airhostess escorts in Jaipur


Housewife Jaipur Escorts
Jaipur College girls escorts
College Girls Escorts in Jaipur
High Class Escorts Service in Jaipur
Jaipur Busty Call Girls
Busty Jaipur Escorts
Jaipur Call Girls Service
Jaipur High Class Call Girls
Jaipur Escorts Service
Escorts Service in Jaipur
Nude Model In Jaipur

Jaipur Escorts Girls said...

Bhankrota Escorts
Jhotwara Escorts
Khatipura Escorts
Mahesh Nagar Escorts
Malviya Nagar Escorts
Raja Park Escorts
Pratap Nagar Escorts
Nirman Nagar Escorts
Narayan Vihar Escorts
Mansarovar Escorts



Sangner Escorts
Shyam Nagar Escorts
Sindhi Camp Escorts
Sodala Escorts
Tonk Road Escorts
Vivek Vihar Escorts
Vaishali Nagar Escorts
Pink City Escorts
Hyderabad Escorts
Hyderabad Escorts
Goa Escorts

Jaipur Escorts Girls said...

Book Now (www.jaipurescortscity.com) a premium call girl from the Best Jaipur escort service agency. Hire a hot escort model for 100% sexual satisfaction—service available 24/7 hours.
Udaipur Escorts
Pushkar Escorts
Lucknow Escorts
Jaisalmer Escorts
Ajmer Escorts
Bikaner Escorts
Dholpur Escorts
Kota Escorts
Jodhpur Escorts



Adarsh Nagar Escorts
Ajmer Road Call Girls Escorts Services
Bais Godam Escorts
Bajaj Nagar Escorts
Banipark Escorts
Jagatpura Escorts
Gopalpura Escorts Service
Dirgapur Escorts Service
Civil Lines Escorts
Chitrakoot Escorts

Escorts Service Kolkata said...

escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |
escorts service in kolkata |

Unknown said...


Thank you a lot for sharing this with all of us you really recognise what you’re speaking approximately!
Bookmarked. Kindly additionally seek advice from my website animedao =).We will have a link exchange arrangement among us,
https://animedaohd.com/

Nitu said...

Wow, you have beautifully decorated this post. I really appreciate it very much. People like you also exist in the world. Who share everything. And there are some people who do not share anything with anyone. I wish today's youth wrote your kind post, thank you very much.http://femaleescortgurugram.com/index.html
http://femaleescortgurugram.com/about.html
http://femaleescortgurugram.com/gallery.html
http://femaleescortgurugram.com/services.html
http://femaleescortgurugram.com/rates.html
http://femaleescortgurugram.com/blog.html
http://femaleescortgurugram.com/contact.html
http://femaleescortgurugram.com/noida-call-girls.html
http://femaleescortgurugram.com/manesar-call-girls.html

Anupama Watch Online said...

Sasural Simar Ka 2 is an Indian television drama series that premiered on Monday
26 April 2021 on Colors TV, right after the completion of launch of 10 year of fomer

Sasural Simar Ka 2 Online

Bahis Forum said...

Yatırım şartsız bedava bonus veren sitelerin tamamına sitemizden ulaşabilirsiniz.

Bhagya Lakshmi said...

Watch the last seven days' episodes of Bhagya Laxmi online in full HD quality,
anytime anywhere on zee5 and Zee tv official website and youtube channel free.

Bhagya Lakshmi

k9Pedia said...

What Is The Cost Of iPhone 13 Pro Max?
https://sitarganjtv.com/what-is-the-cost-of-iphone-13-pro-max/

It is speculated that Apple will double the top storage capacity of the iPhone 13 from last 512GB to 1TB. According to rumors about the iPhone 13 Series, we can assume that the 13 Series will include a phone with a display size that is closer if not slightly bigger than the iPhone 12 Series.

Data Science Chennai said...

This is additionally a generally excellent post which I truly delighted in perusing. It isn't each day that I have the likelihood to see something like this.. data science course in chennai

«Oldest ‹Older   601 – 654 of 654   Newer› Newest»