Clouds
Home

J2EE Overview

J2EE Servlet 1

J2EE Servlet 2

J2EE JSP

J2EE JDBC

J2EE JNDI LDAP

J2EE RMI

J2EE EJB

J2EE JMS

J2EE XML

J2EE STRUTS

J2EE SERVERS

J2EE Best Practices

J2EE Logging

J2EE Testing

J2EE Deployment

J2EE Development Process

EJB Interview Questions


What is the role of EJB 2.x in J2EE ?

EJB 2.x (Enterprise JavaBeans) is widely adopted server side component architecture for J2EE.
  • EJB is a remote, distributed multi-tier system and supports protocols like JRMP, IIOP, and HTTP etc.
  • It enables rapid development of reusable, versatile, and portable business components (i.e. across middleware), which are transactional and scalable.
  • EJB is a specification for J2EE servers. EJB components contain only business logic and system level programming and services like transactions, security, instance pooling, multi-threading, persistence etc are managed by the EJB Container and hence simplify the programming effort.
  • Message driven EJBs have support for asynchronous communication.
Note: Having said that EJB 2.x is a widely adopted server side component, EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO (Plain Old Java Object) persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML based configuration files and eliminates the need for the rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the beanís business interface, O/R mapping information, resource references etc. So, for future developments look out for EJB 3.0 and/or Hibernate framework.

What is the difference between EJB and JavaBeans ?

Both EJBs and JavaBeans have very similar names but this is where the similarities end.

JavaBeans

  • The components built based on JavaBeans live in a single local JVM (i.e. address space) and can be either visual (e.g. GUI components like Button, List etc) or non-visual at runtime.
  • No explicit support exists for services like transactions etc.
  • JavaBeans are fine-grained components, which can be used to assemble coarse-grained components or an application.
  • Must conform to JavaBeans specification.

Enterprise JavaBeans (EJB)

  • The Enterprise JavaBeans are non-visual distributable components, which can live across multiple JVMs (i.e. address spaces).
  • EJBs can be transactional and the EJB servers provide transactional support.
  • EJBs are coarse-grained components that can be deployed as is or assembled with other components into larger applications. EJBs must be deployed in a container that provides services like instance pooling, multi-threading, security, life-cycle management, transactions etc
  • Must conform to EJB specification.

Explain EJB architecture ?

EJB Container:

EJBs are software components, which run in an environment called an EJB container. An EJB cannot function outside an EJB Container. The EJB container hosts and manages an Enterprise JavaBean in a similar manner that a Web container hosts a servlet or a Web browser hosts a Java Applet. The EJB container manages the following services so that the developer can concentrate on writing the business logic:
  • Transactions
  • Persistence
  • EJB instance pooling
  • Security
  • Concurrent access (or multi-threading)
  • Remote access

Design pattern:

EJBs use the proxy design pattern to make remote invocation (i.e. remote proxy) and to add container managed services like security and transaction demarcation.

EJBContext:

Every bean obtains an EJBContext object, which is a reference directly to the container. The EJB can request information about its environment like the status of a transaction, a remote reference to itself (an EJB cannot use 'this' to reference itself) etc.

Deployment Descriptor:

The container handles all the above mentioned services declaratively for an EJB based on the XML deployment descriptor (ejb-jar.xml). When an EJB is deployed into a container the deployment descriptor is read to find out how these services are handled.

EJB:

The EJB architecture defines 3 distinct types of Enterprise JavaBeans.
  • Session beans.
  • Entity beans.
  • Message-driven beans.
The session and entity beans are invoked synchronously by the client and message driven beans are invoked asynchronously by a message container such as a Queue or a Topic.

What are the different kinds of enterprise beans ?

Session Bean:

It is a non-persistent object that implements some business logic running on the server. Session beans do not survive system shut down. There are two types of session beans
  • Stateless session beans (i.e. each session bean can be reused by multiple EJB clients).
  • Stateful session beans (i.e. each session bean is associated with one EJB client).

Entity Bean:

It is a persistent object that represents object views of the data, usually a row in a database. They have the primary key as a unique identifier. Multiple EJB clients can share each entity bean. Entity beans can survive system shutdowns. Entity beans can have two types of persistence
  • Container-Managed Persistence (CMP) - The container is responsible for saving the beanís state.
  • Bean-Managed Persistence (BMP) : The entity bean is responsible for saving its own state.

Message-driven Bean:

It is integrated with the Java Message Service (JMS) to provide the ability to act as a message consumer and perform asynchronous processing between the server and the message producer.

What is the difference between session and entity beans ?

Session Beans

  • Use session beans for application logic.
  • Expect little reuse of session beans.
  • Session beans control the workflow and transactions of a group of entity beans.
  • Life is limited to the life of a particular client. Handle database access for a particular client.
  • Do not survive system shut downs or server crashes.

Entity Beans

  • Use entity beans to develop persistent object model.
  • Insist on reuse of entity beans.
  • Domain objects with a unique identity (i.e.-primary key) shared by multiple clients.
  • Persist across multiple invocations. Handles database access for multiple clients.
  • Do survive system shut downs or server crashes.

What is the difference between stateful and stateless session beans ?

Stateless Session Beans

  • Do not have an internal state. Can be reused by different clients.
  • Need not be activated or passivated since the beans are pooled and reused.

Stateful Session Bean

  • Do have an internal state. Reused by the same client.
  • Need to handle activation and passivation to conserve system memory since one session bean object per client.

What is the difference between Container Managed Persistence (CMP) and Bean Managed Persistence (BMP) entity beans ?

Container Managed Persistence (CMP)

  • The container is responsible for persisting state of the bean.
  • Container needs to generate database (SQL) calls.
  • The bean persistence is independent of its database (e.g. DB2, Oracle, Sybase etc). So it is portable from one data source to another.

Bean Managed Persistence (BMP)

  • The bean is responsible for persisting its own state.
  • The bean needs to code its own database (SQL) calls.
  • The bean persistence is hard coded and hence may not be portable between different databases (e.g. DB2, Oracle etc).

Can an EJB client invoke a method on a bean directly ?

An EJB client should never access an EJB directly. Any access is done through the container. The container will intercept the client call and apply services like transaction, security etc prior to invoking the actual EJB.

How does an EJB interact with its container and what are the call-back methods in entity beans ?

EJB interacts with its container through the following mechanisms

Call-back Methods:

Every EJB implements an interface (extends EnterpriseBean) which defines several methods which alert the bean to various events in its lifecycle. A container is responsible for invoking these methods. These methods notify the bean when it is about to be activated, to be persisted to the database, to end a transaction, to remove the bean from the memory, etc. For example the entity bean has the following call-back methods:

public interface javax.ejb.EntityBean {
public void setEntityContext(javax.ejb.EntityContext c);
public void unsetEntityContext();
public void ejbLoad();
public void ejbStore();
public void ejbActivate();
public void ejbPassivate();
public void ejbRemove();
}


EJBContext:

It provides methods for interacting with the container so that the bean can request information about its environment like the identity of the caller, security, status of a transaction, obtains remote reference to itself etc. e.g. isUserInRole(), getUserPrincipal(), isRollbackOnly(), etc

JNDI:

Java Naming and Directory Interface allows EJB to access resources like JDBC connections, JMS topics and queues, other EJBs etc.

What is the difference between EJB 1.1 and EJB 2.0 ? What is the difference between EJB 2.x and EJB 3.0 ?

EJB 2.0 has the following additional advantages over the EJB 1.1

Local interfaces:

These are beans that can be used locally, that means by the same Java Virtual Machine, so they do not required to be wrapped like remote beans, and arguments between those interfaces are passed directly by reference instead of by value. This improves performance.

EJBHome methods:

Entity beans can declare ejbHomeXXX("") methods that perform operations related to the EJB component but that are not specific to a bean instance. The ejbHomeXXX("") method declared in the bean class must have a matching home method XXXX("") in the home interface.

Message Driven Beans (MDB):

It is a completely new enterprise bean type, which is designed specifically to handle incoming JMS messages.

New CMP Model.

It is based on a new contract called the abstract persistence schema, which will allow the container to handle the persistence automatically at runtime.

EJB Query Language (EJB QL):

It is a SQL-based language that will allow the new persistence schema to implement and execute finder methods. EJB QL also used in new query methods ejbSelectXXX(""), which is similar to ejbFindXXXX("") methods except that it is only for the bean class to use and not exposed to the client (i.e. it is not declared in the home interface)

Let's look at some of the new features on EJB 2.1

Container-managed timer service:

The timer service provides coarse-grained, transactional, time-based event notifications to enable enterprise beans to model and manage higher-level business processes.

Web Service support:

EJB 2.1 adds the ability of stateless session beans to implement a Web Service endpoint via a Web Service endpoint interface.

EJB-QL:

Enhanced EJB-QL includes support for aggregate functions and ordering of results.

Current EJB 2.x model is complex for a variety of reasons:
  • You need to create several component interfaces and implement several unnecessary call-back methods.
  • EJB deployment descriptors are complex and error prone.
  • EJB components are not truly object oriented, as they have restrictions for using inheritance and polymorphism.
  • EJB modules cannot be tested outside an EJB container and debugging an EJB inside a container is very difficult.

What are the implicit services provided by an EJB container ?

Lifecycle Management:

Individual enterprise beans do not need to explicitly manage process allocation, thread management, object activation, or object destruction. The EJB container automatically manages the object lifecycle on behalf of the enterprise bean.

State Management:

Individual enterprise beans do not need to explicitly save or restore conversational object state between method calls. The EJB container automatically manages object state on behalf of the enterprise bean.

Security:

Individual enterprise beans do not need to explicitly authenticate users or check authorization levels. The EJB container automatically performs all security checking on behalf of the enterprise bean.

Transactions:

Individual enterprise beans do not need to explicitly specify transaction demarcation code to participate in distributed transactions. The EJB container can automatically manage the start, enrolment, commitment, and rollback of transactions on behalf of the enterprise bean.

Persistence:

Individual enterprise beans do not need to explicitly retrieve or store persistent object data from a database. The EJB container can automatically manage persistent data on behalf of the enterprise bean.

What are transactional attributes ?

EJB transactions are a set of mechanisms and concepts, which insures the integrity and consistency of the database when multiple clients try to read/update the database simultaneously. Transaction attributes are defined at different levels like EJB class, a method within a class or segment of a code within a method. The attributes specified for a particular method take precedence over the attributes specified for a particular EJB class. Transaction attributes are specified declaratively through EJB deployment descriptors. Unless there is any compelling reason, the declarative approach is recommended over programmatic approach where all the transactions are handled programmatically. With the declarative approach, the EJB container will handle the transactions.

What are isolation levels ?

Isolation levels provide a degree of control of the effects one transaction can have on another concurrent transaction. Since concurrent effects are determined by the precise ways in which, a particular relational database handles locks and its drivers may handle these locks differently. The semantics of isolation mechanisms based on these are not well defined. Nevertheless, certain defined or approximate properties can be specified as follows:

TRANSACTION_SERIALIZABLE

Strongest level of isolation. Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. Can produce deadlocks.

TRANSACTION_REPEATABLE_READ

Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom records can be inserted into the data set by another user and are included in later reads in the current transaction.

TRANSACTION_READ_COMMITTED

Can't read uncommitted data by another transaction. Shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction resulting in non-repeatable reads and phantom records.

TRANSACTION_READ_UNCOMMITTED

Can read uncommitted data (dirty read) by another transaction, and nonrepeatable reads and phantom records are possible. Least restrictive of all isolation levels. No shared locks are issued and no exclusive locks are honored.

Isolation levels are not part of the EJB specification. They can only be set on the resource manager either explicitly on the Connection (for bean managed persistence) or via the application server specific configuration. The EJB specification indicates that isolation level is part of the Resource Manager. As the transaction isolation level increases, likely performance degradation follows, as additional locks are required to protect data integrity. If the underlying data does not require such a high degree of integrity, the isolation level can be lowered to improve performance.

What is a distributed transaction? What is a 2-phase commit?

A Transaction (Refer Q43 in Enterprise section) is a series of actions performed as a single unit of work in which either all of the actions performed as a logical unit of work in which, either all of the actions are performed or none of the actions. A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A distributed transaction is an ACID transaction between two or more independent transactional resources like two separate databases. For the transaction to commit successfully, all of the individual resources must commit successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A 2-phase commit is an approach for committing a distributed transaction in 2 phases.
  • Phase 1 is prepare: Each of the resources votes on whether itís ready to commit usually by going ahead and persisting the new data but not yet deleting the old data.
  • Phase 2 is committing: If all the resources are ready, they all commit after which old data is deleted and transaction can no longer roll back. 2-phase commit ensures that a distributed transaction can always be committed or always rolled back if one of the databases crashes. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers. Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XAcompliant transaction manager.

What is dooming a transaction ?

A transaction can be doomed by the following method call ejbContext.setRollbackOnly(); The above call will force transaction to rollback. The doomed transactions decrease scalability and if a transaction is doomed why perform compute intensive operations? So you can detect a doomed transaction as shown below:

public void doComputeIntensiveOperation() throws Exception {
    if ( ejbContext.getRollbackOnly() ) {
      return; // transaction is doomed so return (why unnecessarily perform compute intensive // operation)
    } else {
      performComplexOperation();
    }
}


How to design transactional conversations with session beans ?

A stateful session bean is a resource which has an in memory state which can be rolled back in case of any failure. It can participate in transactions by implementing SessionSynchronization.
The uses of SessionSynchronization are:
  • Enables the bean to act as a transactional resource and undo state changes on failure.
  • Enables you to cache database data to improve performance.

Explain exception handling in EJB ?

Java has two types of exceptions:
  • Checked exception: derived from java.lang.Exception but not java.lang.RuntimeException.
  • Unchecked exception: derived from java.lang.RuntimeException thrown by JVM.
EJB has two types of exceptions:
  • System Exception: is an unchecked exception derived from java.lang.RuntimeException. An EJBException is an unchecked exception, which is derived from java.lang.RuntimeException.
    A System Exception is thrown by the system and is not recoverable. For example EJB container losing connection to the database server, failed remote method objects call etc. Because the System Exceptions are unpredictable, the EJB container is the only one responsible for trapping the System Exceptions. The container automatically wraps any RuntimeException in RemoteException, which subsequently gets thrown to the caller (i.e. client). In addition to intercepting System Exception the container may log the errors.
  • Application Exception: is specific to an application and thrown because of violation of business rules (e.g. InsufficierntFundException etc). An Application Exception is a checked exception that is either defined by the bean developer and does not extend java.rmi.RemoteException, or is predefined in the javax.ejb package (i.e. CreateException, RemoveException, ObjectNotFoundException etc). An Application Exception is specific to an application and is thrown because of violation of business rules. The client should be able to determine how to handle an Application Exception. If the account balance is zero then an Application Exception like InsufficientFundException can be thrown. If an Application Exception should be treated as a System Exception then it needs to be wrapped in an EJBException, which extends java.lang.RuntimeException so that it can be managed properly (e.g. rolling back transactions) and propagated to the client.

How do you rollback a container managed transaction in EJB ?

The way the exceptions are handled affects the way the transactions are managed. When the container manages the transaction, it is automatically rolled back when a System Exception occurs. This is possible because the container can intercept System Exception. However when an Application Exception occurs, the container does not intercept it and therefore leaves it to the code to roll back using ctx.setRollbackOnly().
Be aware that handling exceptions in EJB is different from handling exceptions in Java. The Exception handling best practice tips are:
  • If you cannot recover from System Exception let the container handle it.
  • If a business rule is violated then throw an application exception.
  • If you want to rollback a transaction on an application exception then catch the application exception and throw an EJBException or use ctx.setRollbackOnly();

    What is the difference between optimistic and pessimistic concurrency control ?

    Pessimistic Concurrency

  • A pessimistic design assumes conflicts will occur in the database tables and avoids them through exclusive locks etc.
  • EJB (also non-EJB) locks the source data until it completes its transaction.
    • Provides reliable access to data.
    • Suitable for short transactions.
    • Suitable for systems where concurrent access is rare.
  • The pessimistic locking imposes high locking overheads on the server and lower concurrency.

    Optimistic Concurrency

  • An optimistic approach assumes conflicts wonít occur, and deal with them when they do occur.
  • EJB (also non-EJB) implements a strategy to detect whether a change has occurred. Locks are placed on the database only for a small portion of the time.
    • Suitable for long transactions.
    • Suitable for systems requiring frequent concurrent accesses.
  • The optimistic locking is used in the context of cursors. The optimistic locking works as follows:
    • No locks are acquired as rows are read.
    • No locks are acquired while values in the current row are changed.
    • When changes are saved, a copy of the row in the database is read in the locked mode.
    • If the data was changed after it was read into the cursor, an error is raised so that the transaction can be rolled back and retried.

    How can we determine if the data is stale (for example when using optimistic locking) ?

    We can use the following strategy to determine if the data is stale:
    • Adding version numbers
      • Add a version number (Integer) to the underlying table.
      • Carry the version number along with any data read into memory (through value object, entity bean etc).
      • Before performing any update compare the current version number with the database version number.
      • If the version numbers are equal update the data and increment the version number.
      • If the value object or entity bean is carrying an older version number, reject the update and throw an exception.
    • Adding a timestamp to the underlying database table.
    • Comparing the data values.
    These techniques are also quite useful when implementing data caching to improve performance. Data caches should regularly keep track of stale data to refresh the cache. These strategies are valid whether you use EJB or other persistence mechanisms like JDBC, Hibernate etc.

    What are not allowed within the EJB container ?

    In order to develop reliable and portable EJB components, the following restrictions apply to EJB code implementation:
    • Avoid using static non-final fields. Declaring all static fields in EJB component as final is recommended. This enables the EJB container to distribute instances across multiple JVMs.
    • Avoid starting a new thread (conflicts with EJB container) or using thread synchronization (allow the EJB container to distribute instances across multiple JVMs).
    • Avoid using AWT or Swing functionality. EJBs are server side business components.
    • Avoid using file access or java.io operations. EJB business components are meant to use resource managers such as JDBC to store and retrieve application data. But deployment descriptors can be used to store .
    • Avoid accepting or listening to socket connections. EJB components are not meant to provide network socket functionality. However the specification lets EJB components act as socket clients or RMI clients.
    • Avoid using the reflection API. This restriction enforces Java security.
    • Can't use custom class loaders.

    Discuss EJB container security ?

    EJB components operate inside a container environment and rely heavily on the container to provide security. The four key services required for the security are:
  • Identification: In Java security APIs this identifier is known as a principal.
  • Authentication: To prove the identity one must present the credentials in the form of password, swipe card, digital certificate, finger prints etc.
  • Authorization (Access Control): Every secure system should limit access to particular users. The common way to enforce access control is by maintaining security roles and privileges.
  • Data Confidentiality: This is maintained by encryption of some sort. It is no good to protect your data by authentication if someone can read the password. The EJB specification concerns itself exclusively with authorization (access control). An application using EJB can specify in an abstract (declarative) and portable way that is allowed to access business methods. The EJB container handles the following actions:
    • Find out the Identity of the caller of a business method.
    • Check the EJB deployment descriptor to see if the identity is a member of a security role that has been granted the right to call this business method.
    • Throw java.rmi.RemoteException if the access is illegal.
    • Make the identity and the security role information available for a fine grained programmatic security check.
    • Optionally log any illegal access.
    There are two types of information the EJB developer has to provide through the deployment descriptor.
    • Security roles
    • Method permissions

    What are EJB best practices ?

  • Use local interfaces that are available in EJB2.0 if you deploy both the EJB client and the EJB in the same server. Use vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs operate as local. [Extreme care should be taken not to affect the functionality by switching the application, which was written and tested in pass-by-reference mode to pass-by-value without analyzing the implications and re-testing the functionality.
  • Wrap entity beans with session beans to reduce network calls and promote declarative transactions. Where possible use local entity beans and session beans can be either local or remote. Apply the appropriate EJB design patterns
  • Cache ejbHome references to avoid JNDI look-up overhead using service locator pattern.
  • Handle exceptions appropriately.
  • Avoid transaction overhead for non-transactional methods of session beans by declaring transactional attribute as "Supports".
  • Choose plain Java object over EJB if you do not want services like RMI/IIOP, transactions, security, persistence, thread safety etc. There are alternative frameworks such as Hibernate, Spring etc.
  • Choose Servletís HttpSession object rather than stateful session bean to maintain client state if you do not require component architecture of a stateful bean.
  • Apply Lazy loading and Dirty marker strategies

    JMS Interview Questions >>>




    Home Clouds