Difference between EJB and Servlet? - servlets

We are using ejb 2.1 to expose as a webservice using apache axis2.I have read in codebranch website that both are serverside components where in ejb can be run in more than one server unlike servlets..but I didn't get clear picture of difference.

Let me quote this old (but good) comparison.
Enterprise JavaBeans are components meant to encapsulate business logic. They do not handle presentation and have a precise set of restrictions they must obey. An EJB may not manage threads, access files with the java.io package, have a GUI, accept socket connections, or load native libraries. These restrictions are imposed because EJBs execute inside an EJB container, roughly analogous to the way servlets execute in a servlet container. Where servlets can be used to perform many arbitrary tasks, including the generation of HTML pages, EJBs are used almost entirely as business objects. A session bean represents a client for a session or transaction and an entity bean represents a persistent business object that is usually stored in a database. Unlike servlets, a single session bean may exist per client. A single servlet may serve many clients. A session bean usually mediates client access to entity beans, shielding the client from the details of managing state.

I got exact answer Both are server side entities.EJB is designed by wrapping RMI API's.EJB is a service at Enterprise level.Main advantage that EJB can be a webservice which can deployed anywhere in the world.EJB is servicelayer enity which can even used by servlets.
We can have plain java in the service layer but differance that EJB has is it(EJB) can be alone deployed in any server unlike plain-java service layer.

Related

Is a local client passed a direct reference to a EJB LocalBean?

When a local client gets a reference to a LocalBean, does the container provide a direct reference to bean instance? If not, what is provided?
Pointers to specs and authentic sources would be highly appreciated.
The spec does not prescribe that explicitly as I see, but injected references to EJBs are normally interface-based proxies. That's necessary for providing container services, like transaction management and timeout control, picking an instance from the pool in case of SLSB, calling user interceptors if any, etc.
While the spec only tells something rather neutral:
The container is responsible for making the business interfaces and/or
home interfaces of its deployed enterprise beans available to the
client through dependency injection and/or through lookup in the JNDI
namespace.
You can easily check that BTW, for example with debugger.

EJB & safe publication

I have been reading lately about safe publication of Java objects (e.g. here: http://shipilev.net/blog/2014/safe-public-construction/).
Until now I was trusting EJB container without questions when relying on container managed concurrency.
Now I'm wondering
1) how an EJB container can make sure that the EJB itself is published safely?
2) how an EJB container can make sure that objects created by its EJBs are published safely (e.g. EJB instance vars)?
E.g. stateless session bean can be accessed by different threads over time (I'm not necesseraly saying simultaneously), so unsafe publication is a potential issue.
For 1), I roughly see possibilities, e.g. by wrapping the EJB and using some volatile accesses to garantuee total order.
For 2), I don't see how EJB container can enforce it.
Maybe it is forbidden by the EJB 3.1 spec to keep instance variables in the EJB if it can be accessed by different threads?
Maybe the statement "don't worry about concurrency in container managed EJB" is not true, and I should use safe publication patterns (including volatile and/or final keywords) in the class definitions of the classes used in my EJB instance vars?
I'm surpirsed I missed this fundamental problemacy for that many years as a Java developer.
Regards,
Lars
If an EJB container is reusing instances, it must store them in a thread-safe object pool, which must use some synchronization (synchronized, compare-and-swap, etc.), which will ensure that everything written by the first thread will "happen-before" everything that happens on the second thread. EJB developers do not need to worry about synchronization (unless they're using singleton session beans with bean-managed concurrency or the EJB is going outside the scope of the EJB spec by storing data in static variables).

circular ejb dependencies: what does the spec say?

I know from experience that injection of circular dependencies in EJB do work, at least in some application servers.
I've done it multiple times with self-injection (e.g. to get an EJB proxy for #TransactionAttribute, #RolesAllowed, #Asynchronous etc. to work).
I've done it with more complex graphs too (A->B->A etc.), which obviously work too.
I've done it at least in Glassfish 3/4, Weblogic, and JBoss 7.3. Maybe Weblogic, not sure.
Now, I've been trying to find some precise guarantee from the specification, without success. There are provisions for this in CDI, but I couldn't find any explanation on why it works for EJBs. Is there some indirect one, maybe?
I'm looking from some references from EJB specifications regarding this.
I don't believe the EJB specification explicitly disallows self-injection, which means it implicitly allows it since there is no reason for the bean's own interface to be different from the interface of some other EJB. In practice, self-injection can only work for stateless (and singleton in EJB 3.1) and not stateful since each lookup/injection of a stateful bean creates a new instance, which would result in infinite recusion. For stateful, you can inject SessionContext and use the getter methods to return a "self-proxy" rather than using injection. This technique also works for stateless/singleton, and it might be marginally faster than using injection (particularly if you cache the result in an instance field the same as injection) since the EJB container can probably return a self-proxy more directly than going through injection/JNDI.
The only additional authority I can give to this answer is that I was one of the primary developers/maintainers of the EJB container in WebSphere Application Server for 5 years. To add to your list of products, I know that self-injection also works in practice on WebSphere Application Server.

Singleton vs Single Thread

Normally Servlets are initiated just once and web container simple spawns a new thread for every user request. Let's say if I create my own web container from scratch and instead of Threads, I simply create Servlets as Singleton. Will I be missing anything here? I guess, in this case, the singleton can only service one user request at a time and not multiple.
Normally Servlets are initiated just once and web container simple spawns a new thread for every user request.
The first statement is true, but the second actually not. Normally, threads are been created once during applications startup and kept in a thread pool. When a thread has finished its request-response processing job, it will be returned to the pool. That's also why using ThreadLocal in a servletcontainer must be taken with high care.
Let's say if I create my own web container from scratch and instead of Threads, I simply create Servlets as Singleton. Will I be missing anything here?
They does not necessarily need to follow the singleton pattern. Just create only one instance of them during application's startup and keep them in memory throughout application's lifetime and just let all threads access the same instance.
I guess, in this case, the singleton can only service one user request at a time and not multiple.
This is not true. This will only happen when you synchronize the access to the singleton's methods on an application-wide lock. For example by adding the synchronized modifier to the method of your servlet or a synchronized(this) in the manager's method who is delegating the requests to the servlets.
JavaEE used to have a mechanism for this - a marker interface called SingleThreadModel that your servlet could implement:
Ensures that servlets handle only one request at a time. This interface has no methods.
If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. This interface is deprecated in Servlet API version 2.4.
Containers could use this to instantiate a new servlet for each request, or maintain a pool of them, if they chose to.
This was deprecated in Servlet 2.4, for the reasons documented above. Those same reasons still apply to your question.
That's basically it.
I would question the motivations for creating your own container, with so many available for a wide range of purposes.

Is it safe to inject an EJB into a servlet as an instance variable?

We all know that in the web tier there is the possibility that only a single instance of a given Servlet exists which services multiple requests. This can lead to threading issues in instance variables.
My question is, is it safe to inject an EJB using the #EJB annotation into a servlet as an instance variable?
My initial instinct would be no, under the assumption that the same instance of the EJB would service multiple requests at the same time. It would seem that this would also be the instinct of a number of other programmers: Don't inject to servlets
However have I jumped to the wrong conclusion. Clearly what is injected into the servlet is a proxy, under the hood does the container actually service each request with a different instance and maintain thread safety? As this forum would suggest: Do inject to servlets
There seems to be a lot of conflicting opinions. WHICH IS CORRECT???
It is safe to inject an EJB in a Servlet as a Servlet instance variable, as long as the EJB is Stateless. You MUST NEVER inject a Stateful Bean in a Servlet.
You must implement your EJB stateless in that it doesn't hold any instance variable which itself holds a stateful value (like Persistence Context). If you need to use the persistence context, then you must get an instance of it IN the methods of the EJB. You can do that by having a PersistenceContextFactory as a EJB instance Variable and then you get an instance of the entity manager from the Factory in the method of the EJB.
The PersistenceContextFactory is thread-safe, thus it can be injected in an instance variable.
As long as you comply to the above mentioned rules, it should be thread-safe to inject a Stateless Bean in a Servlet
Your reference "Don't inject to servlets" mentions nothing about ejbs or #ejb annotation. It talks about not thread safe objects such as PersistenceContext.
Per EJB spec you can access ejbs from variety of remote clients including servlets (EJB 3.0 Specification (JSR-220) - Section 3.1). Injecting ejb using #EJB annotation is a method of obtaining EJB interface via dependency injection (section 3.4.1) which is alternative to looking up ejb objects in the JNDI namespace. So there is nothing special about #EJB annotation with respect to EJBs obtained.
So, based on EJB 3.0 Spec, it's a standard practice to obtain ejbs from servlets using #EJB annotation.
It's a mixed bag.
Stateless session beans may be injected and are safe. This is because even if a single instance of a stub is used, access to the methods will be serialized by the container.
I think what inferreddesign says is not true. It doesn't matter if the stateless session bean uses a persistence context. Only one caller will ever access a single bean instance at the same time, so even though the persistence context is not thread safe, the EJB guards against multiple access to it. Think of it as if every session bean method has the synchronized keyword applied to it.
The main problem with injecting an EJB in a Servlet I think is performance. The single stub instance will become a major area of contention when multiple requests are queuing up while waiting for a session bean method to be executed for them.
I think the simple answer is that you aren't guaranteed that it is safe.
The reason for this is that there is nothing explicit in the EJB specification that says EJB home interfaces have to be thread safe. The spec outlines the behaviour of the server side part only. What you will probably find is that the client skeletons are actually thread safe but you would need to look at how they are implemented by the library you are using. The annotation part will just expand into a service locator so that doesn't buy you anything.

Resources