Interview question and answers on Java and EJB 3

1. What is the difference between normal Java object and EJB

2. What is the difference between JavaBean and EJB
Java Beans is intra-process component
where as EJB is an Inter-Process component
 
JavaBeans is particularly well-suited for asynchronous, intra-application communications among software

3. What is EJB
Enterprise JavaBeans (EJB) is a technology that based on J2EE platform.  
EJBs are server-side components. EJB are used to develop the distributed, transactional and secure applications based on Java technology

4. What is Session Bean. What are the various types of Session Bean
SessionBeans typically are used to represent a client they are of two typse
 
Stateful Session Beans : they maintain conversational state between subsequest calls by a client
 
Stateless Session Bean : consider this as a servlet equivalent in EJB. It is just used to service clients regardless of state and does not maintain any state.

5. What is the difference between Stateful session bean and Stateless session bean
Stateful session beans have the passivated and Active state which the Stateless bean does not have.

6. What is the life cycle of Stateful session bean
a Stateful Session Bean has three states. Does not exists, Method Ready and Passivated states.
 
Like Stateless beans, when the Stateful Session Bean hasnt been instantiated yet (so it is not an instance in memory) is it in the Does not exists state.
 
Once a container creates one or more instances of a Stateful Session Bean it sets them in a Method Ready state. In this state it can serve requests from its clients. Like Stateless Session Beans, a new instance is created (Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with ejbCreate().
 
During the life of a Stateful Session Bean, there are periods of inactivity. In these periods, the container can set the bean to the Passivate state. This happens through the ejbPassivate() method. From the Passivate state the bean can be moved back to the Method Ready state, via ejbActivate() method, or can go directly to the Does Not Exists state with ejbRemove().  

Ans 2 :
doesnot exsist
2. exsists
3. passivate
 
invoke ejbcreate()
set the sessioncontext()
call create()
 
if the session idle call ejbPassivate()
to get back to session call ejbActivate()
 
to end the session call ejbRemove()
then call remove()

7. What is the life cycle of Stateless session bean
stateless session bean has only two states: Does Not Exists and Method Ready Pool.
 
A bean has not yet instantiated (so it is not an instance in memory) when it is in the Does Not Exists state.
 
When the EJB container needs one or more beans, it creates and set them in the Method Ready Pool state. This happens through the creation of a new instance (Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method.
 
The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exists state

ans 2:
dose not exsist
2. exsist
 
to start the session
set the sessionContext()
call create()
 
to end session
call remove

8. What are the call back methods in Session bean
Session bean callback methods differ whether it is Stateless or stateful Session bean. Here they are.
 
Stateless Session Bean
1. setSessionContext()
2. ejbCreate()
3. ejbRemove()
 
Stateful Session Bean  
 
1. setSessionContext()
2.ejbCreate()
3.ejbPassivate()
4.ejbActivate()
5.ejbRemove()

9. When you will chose Stateful session bean and Stateless session bean
stateful session bean is used when we need to maintain the client state . Where stateless session bean will not have a client state it will be in pool. Example of statefull session is Shoping cart site where we need to maintain the client state .

10. What is Entity Bean. What are the various types of Entity Bean
Entity bean represents the real data which is stored in the persistent storage like Database or file system. For example, There is a table in Database called Credit_card. This table contains credit_card_no,first_name, last_name, ssn as colums and there are 100 rows in the table. Here each row is represented by one instance of the entity bean and it is found by an unique key (primary key) credit_card_no.
 
There are two types of entity beans.
1) Container Managed Persistence(CMP)  
2) Bean Managed Presistence(BMP)

11. What is the difference between CMP and BMP
CMP means Container Managed Persistence. When we write CMP bean , we dont need to write any JDBC code to connect to Database. The container will take care of connection our enitty beans fields with database. The Container manages the persistence of the bean. Absolutely no database access code is written inside the bean class.  
BMP means Bean Managed Persistence. When we write BMP bean, it is programmer responsiblity to write JDBC code to connect to Database.

12. What is the lifecycle of Entity Bean
The following steps describe the life cycle of an entity bean instance
 
An entity bean instances life starts when the container creates the instance using newInstance and then initialises it using setEntityContext.
 
The instance enters the pool of available instances. Each entity bean has its own pool. While the instance is in the available pool, the instance is not associated with any particular entity object identity. Any of these pooled instances may be used to execute finder (ejbFind) or home (ejbHome) methods.  
 
An instance transitions from the pooled state to the ready state when the container selects that instance to service a client call to an entity object. There are two possible transitions from the pooled to the ready state: through the creation of an entity (ejbCreate and ejbPostCreate) or through the activation of an entity (ejbActivate).  
When an entity bean instance is in the ready state, the instance is associated with a specific entity object identity. While the instance is in the ready state, the container can synchronize the instance with its representation in the underlying data source whenever it determines the need to using ejbLoad and ejbStore methods. Business methods can also be invoked zero or more times on an instance. An ejbSelect method can be called by a business method, ejbLoad or ejbStore method.  
The container can choose to passivate an entity bean instance within a transaction. To passivate an instance, the container first invokes the ejbStore method to allow the instance to prepare itself for the synchronization of the database state with the instance’s state, and then the container invokes the ejbPassivate method to return the instance to the pooled state.  
There are three possible transitions from the ready to the pooled state: through the ejbPassivate method, through the ejbRemove method (when the entity is removed), and because of a transaction rollback for ejbCreate, ejbPostCreate,or ejbRemove.  
The container can remove an instance in the pool by calling the unsetEntityContext() method on the instance.

13. What are the call back methods in Entity bean
setEntityContext()
2. ejbCreate()
3. ejbPostCreate()
4. ejbActivate()
5. ejbPassivate()
6. ejbRemove()
7. unsetEntityContext()

14. When you will chose CMP and BMP
BMP  
- Bean managed persistence
- Developer has to write persistence code for ejbLoad(),ejbStore() for entity beans
- Should follow this approach only when its bare necessity to write your own persistence logic.Usually container managed persistence is quite sufficient and less error prone.
 
CMP
- Container managed persistence
- Developer maps the bean fields with the database fields in the deployment descriptors.
- Developer need not provide persistence logic (JDBC) within the bean class.
- Containiner manages the bean field to DB field synchronization.
 
The point is only ENTITY beans can have theier pesristence mechanism as CMP or BMP. Session beans, which usually contains workflow or business logic should never have persistence code.Incase you choose to write persistence within your session bean, its usefull to note that the persistence is managed by the container BMP.Session beans cannot be CMP and its not possibel to provide field mapping for session bean.

15. What are advantages and disadvantages of CMP and BMP
CMP::
 
Advantages:
1)Easy to develop and maintain.
2)Relationships can be maintained between different entities.
3)Optimization of SQL code will be done.
4)Larger and more performance applications can be done.
 
Disadvantages:
 
1)Will not support for some nonJDBC data sources,i.e,CICS.
2)Complex queries cannot be developed with EJBQL.
 
 
BMP::
 
Advantages:
1)Support for nonJDBC data sources.
2)Complex queries can be build.
 
Disadvantages:
 
1)Hard to develop and maintain.
2)We cannot maintain the relationships between different entities.
3)Optimization of SQL code cannot be done by the container,because bean it self contains the code.
4)Not appropriate for larger and complex applications.

16. What is difference between EJB 1.1 and EJB 2.0
EJB 2.0 adds the local beans, which are accessible only from within the JVM where beans are running in.
 
In EJB 1.1, we had to implement remote client views for all these beans, even if we had no remote clients.

17. What is Message Driven Bean
Message Driven Bean (MDB) is an enterprise bean which runs inside the EJB container and it acts as Listener for the JMS asynchronous message . It does not have Home and Remote interface as Session or Entity bean. It is called by container when container receives JMS asynchronous message. MDB has to implement MessageListener which has a method onMessage(Message msg). When the container calls the MDB it passes the message to onMesage() method and then MDB process that message.

18. What is the life cycle of MDB
The lifetime of an MDB instance is controlled by the container. Only two states exist: Does not exist and Ready , as illustrated in the following figure:  
   
The life of an MDB instance starts when the container invokes newInstance() on the MDB class to create a new instance. Next, the container calls setMessageDrivenContext() followed by ejbCreate() on the instance. The bean then enters the Ready state and is ready to consume messages.  
 
When a message arrives for the bean, the container invokes the onMessage() method of one of the available instances, passing a Message object in argument. Message s can be consumed and processed concurrently by using multiple instances of the same type.  
 
The container invokes ejbRemove() on the bean instance when it no longer needs the instance. The bean instance can perform clean up operations here.  

19. What is local interface. How values will be passed
If Client and EJB classes are in the same machine ( Same JVM) then we can use Local linterface instead of Remote interface. Since Client and EJB are in same JVM, values are passed by referance.

20. What is the difference between local interface and remote interface
We can describe the following common rules for choosing whether to use remote client view or local client view:
 
When you will potentially use a distributed environment (if your enterprise bean should be independent of its deployment place), you should obviously choose remote client view.
 
Use remote client view when you need to be sure that parameters passed between your EJB and the client (and/or other enterprise beans) should be passed "by value" instead of "by reference." With pass-by-value, the bean will have its own copy of the data, completely separated from the copy of the data at the client. With local client view, you can do pass-by-reference, which means your bean, as well as the client, will work directly with one copy of the data. Any changes made by the bean will be seen by the client and vice versa. Pass-by-reference eliminates time/system expenses for copying data variables, which provides a performance advantage.
 
If you create an entity bean, you need to remember that it is usually used with a local client view. If your entity bean needs to provide access to a client outside of the existing JVM (i.e., a remote client), you typically use a session bean with a remote client view. This is the so-called Session Facade pattern, the goal of which is that the session bean provides the remote client access to the entity bean.
 
If you want to use container-managed relationship (CMR) in your enterprise bean, you must expose local interfaces, and thus use local client view. This is mentioned in the EJB specification.
 
Enterprise beans that are tightly coupled logically are good candidates for using local client view. In other words, if one enterprise bean is always associated with another, it is perfectly appropriate to co-locate them (i.e., deploy them both in one JVM) and organize them through a local interface.

21. What is EJB Query Language
EJB QL is somewat similar to SQL. But ejb ql is used to retrieve data from bean objects where as sql is used to retrieve data from tables.
 

22. What is ACID
ACID is releated to transactions. It is an acronyam of Atomic, Consistent, Isolation and Durable. Transaction must following the above four properties to be a better one
 
Atomic: It means a transaction must execute all or nothing at all.
Consistent: Consistency is a transactional characteristic that must be enforced by both the transactional system and the application developer
Isolation: Transaation must be allowed to run itselft without the interference of the other process or transactions.
Durable: Durablity means that all the data changes that made by the transaction must be written in some type of physical storage before the transaction is successfully completed. This ensures that transacitons are not lost even if the system crashes.

23. What are the various isolation levels in a transaction and differences between them
There are three isolation levels in Transaction. They are 1. Dirty reads 2.Non repeatable reads 3. Phantom reads.
 
Dirrty Reads If transaction A updates a record in database followed by the transaction B reading the record then the transaction A performs a rollback on its update operation, the result that transaction B had read is invalid as it has been rolled back by transaction A.
 
NonRepeatable ReadsIf transaction A reads a record, followed by transaction B updating the same record, then transaction A reads the same record a second time, transaction A has read two different values for the same record.
 
Phantom ReadsIf transaction A performs a query on the database with a particular search criteria (WHERE clause), followed by transaction B creating new records that satisfy the search criteria, followed by transaction A repeating its query, transaction A sees new, phantom records in the results of the second query.

24. What are the various transaction attributes and differences between them
There are six transaction attributes that are supported in EJB.
1. NotSupported
2. Supports
3. Required
4. RequiresNew
5. Mandatory
6. Never

25. What is the difference between activation and passivation
Activation and Passivation is appilicable for only Stateful session bean and Entity bean.  
 
When Bean instance is not used for a while by client then EJB Container removes it from memory and puts it in secondary storage (often disk) so that the memory can be reused. This is called Passivation.
 
When Client calls the bean instance again then Container takes the passivated bean from secondary storage and puts it in memory to serve the client request. This is called Activation.

26. What is Instance pooling
pooling of instances.
 
in stateless session beans and Entity Beans server maintains a pool of instances.whenever server got a request from client, it takes one instance from the pool and serves the client request.

27. What is the difference between HTTPSession and Stateful Session Bean
From a logical point of view, a Servlet/JSP session is similar to an EJB session. Using a session, in fact, a client can connect to a server and maintain his state.
But, is important to understand, that the session is maintained in different ways and, in theory, for different scopes.
 
A session in a Servlet, is maintained by the Servlet Container through the HttpSession object, that is acquired through the request object. You cannot really instantiate a new HttpSession object, and it does not contains any business logic, but is more of a place where to store objects.
 
A session in EJB is maintained using the SessionBeans. You design beans that can contain business logic, and that can be used by the clients. You have two different session beans: Stateful and Stateless. The first one is somehow connected with a single client. It maintains the state for that client, can be used only by that client and when the client "dies" then the session bean is "lost".
 
A Stateless Session Bean does not maintain any state and there is no guarantee that the same client will use the same stateless bean, even for two calls one after the other. The lifecycle of a Stateless Session EJB is slightly different from the one of a Stateful Session EJB. Is EJB Containers responsability to take care of knowing exactly how to track each session and redirect the request from a client to the correct instance of a Session Bean. The way this is done is vendor dependant, and is part of the contract.

28. How do you check whether the session is active in Stateful session bean
In Stateful session bean session is not itself a separate entity. it is contained in the bean it self. So in order to check tht we need the check whether the Stateful session bean is present or not which is done by just invoking the home interface with the jndi
 

29. What is the difference between find and select methods in EJB
A select method is similar to a finder method for Entity Beans, they both use EJB-QL to define the semantics of the method.
They differ in that an ejbSelect method(s) are not exposed to the client and the ejbSelect method(s) can return values that are defined as cmp-types or cmr-types.

30. What are the optional clauses in EJB QL
Three optional clauses are available in EJB Ql.
1. SELECT
2.FROM
3.WHERE
 
The EJB QL must always contain SELECT and FROM clauses. The WHERE clause is optional.
The FROM clause provides declarations for the identification variables based on abstract schema name, for navigating through the schema. The SELECT clause uses these identification variables to define the return type of the query, and the WHERE clause defines the conditional query.

31. What is handle in EJB
A handle is an abstraction of a network reference to an EJB object. A handle is intended to be used as a "robust" persistent reference to an EJB object.

32. What is the difference between JNDI context, Initial context, session context and ejb context
JNDI Context Provides a mechanism to lookup resources on the network
Initial Context constructor provides the initial context.
Session Context has all the information a session bean would require from the container
Entity Context has all the information that an Entity bean would need from a container
Ejb Context contains the information that is common to both the session and entity bean

33. What is the difference between sessioncontext and entitycontext
Session Context Contains information that a Session Bean would require from the container  
Entity Context contains the information that an Entity Bean would require from a container

34. What is the difference between EAR, JAR and WAR file
In J2EE application modules are packaged as EAR, JAR and WAR based on their functionality  
JAR:
EJB modules which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extenstion
WAR
Web modules which contains Servlet class files,JSP FIles,supporting files, GIF and HTML files are packaged as JAR file with .war( web achive) extension
EAR
All above files(.jar and .war) are packaged as JAR file with .ear ( enterprise archive) extension and deployed into Application Server.

35. What is deployment descriptor
Deployment Descriptor is a XML document with .xml extenion. It basically descripes the deployment settings of an application or module or the component. At runtime J2EE server reads the deployment descriptor and understands it and then acts upon the component or module based the information mentioned in descriptor.   
For example EJB module has a deployment descriptor ejb-jar.xml where we mention whether it is session or entity or mesage driven bean and where is the home, remore and Bean classes are located and what type of transaction etc. In a simple word, without deployment descritor the Container ( EJB/Servlet/JSP container) will not know what to do with that module.

36. What is CMR
CMR - Container Managed Relationships allows the developer to declare various types of relationships between the entity beans

37. What is the difference between CMP 1.1 and CMP 2.0
CMR
and sub classing of the CMP bean by the container

38. What is the difference between optimistic locking and pessimistic locking
Optimistic locking assumes that no one would read or change the data while changes are being by a bean
Pessimistic locking would rather lock down the data so that no one can access it

39. What is lazy loading
Lazy loading is a characteristic of an application when the actual loading and instantiation of a class is delayed until the point just before the instance is actually used. The goal is to only dedicate memory resources when necessary by only loading and instantiating an object at the point when it is absolutely needed.
 
Tools such as Eclipse have popularized the lazy-loading approach as they use the facility to control the load and initialization of heavyweight plug-ins. This gives the double bonus of speeding up the initial load time for the application, as not all plug-ins are loaded straightaway; ensuring efficiency as only the plug-ins that are used are loaded at all.  

40. What are the services provided by container
The EJB container provides services to EJB components. The services include transaction, naming, and persistence support.  
 
Transaction support An EJB container must support transactions. EJB specifications provide an approach to transaction management called declarative transaction management. In declarative transaction management, you specify the type of transaction support required by your EJB component. When the bean is deployed, the container provides the necessary transaction support.  
 
 
Persistence support An EJB container can provide support for persistence of EJB components. An EJB component is persistent if it is capable of saving and retrieving its state. A persistent EJB component saves its state to some type of persistent storage (usually a file or a database). With persistence, an EJB component does not have to be re-created with each use.  
 
 
An EJB component can manage its own persistence (by means of the logic you provide in the bean) or delegate persistence services to the EJB container. Container-managed persistence means that the data appears as member data and the container performs all data retrieval and storage operations for the EJB component. See Chapter 27, "Creating Entity Components" for more information.  
 
Naming support An EJB container must provide an implementation of Java Naming and Directory Interface (JNDI) API to provide naming services for EJB clients and components. Naming services provide:  
 
Location transparency Clients can instantiate components by name, and do not need to know the details about the server hosting the component.  
Deployment flexibility Beginning in EJB version 1.1, EJB components can be configured with naming aliases for components and resources such as databases, JavaMail sessions, and JMS message queues. Using aliases simplifies the procedure to deploy the component on a server where the accessed components and resources use different JNDI names.


Comments (0)

Post a Comment
* Your Name:
* Your Email:
(not publicly displayed)
Reply Notification:
Approval Notification:
Website:
* Security Image:
Security Image Generate new
Copy the numbers and letters from the security image:
* Message:

Email to Friend

Fill in the form below to send this article to a friend:

Email to Friend
* Your Name:
* Your Email:
* Friend's Name:
* Friend's Email:
* Security Image:
Security Image Generate new
Copy the numbers and letters from the security image
* Message: