Ejb 3 interview questions: We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.
Java J2EE Interview Questions on Ejb
What do you understand by EJB? Elaborate.
Enterprise JavaBeans (EJB) is a server-side component framework that simplifies the process of building enterprise-class distributed component applications in Java. By using EJB, l» you can write scalable, reliable, and secure applications without writing your own complex distributed component framework. EJB is about rapid application development for the server-side; you can quickly and easily construct server-side components in Java by leveraging a prewritten distributed infrastructure provided by the industry. EJB is designed to support. application portability and reusability across any vendor’s enterprise middleware services.
In short, EJB is a standard for developing and deploying server-side distributed components in Java. It defines an agreement (contract) between components and application servers that enables any component to run in any compliant application server. The three main advantages of EJB are:-
- It is a ubiquitous industry standard;
- Portability is possible; and,
- Rapid application development.
Why has EJB supported only Java thus far?
The EJB framework has supported only Java thus far, unlike the .NET framework that supports multiple languages. The reason for this is not far to seek. Java is one of the best-suited languages for building distributed components for the following reasons:-
(1) Interface/implementation separation: We need a language that supports a clean separation between the interface and implementation mainly to keep the component upgrades and maintenance to a minimum. Java supports this separation at a syntactic level through the interface and class keywords.
(2) Safe and secure: The Java architecture is much safer than traditional programming languages. In Java, if a thread dies, the application stays up. Pointers are not an issue since the language never exposes them to the programmer, Memory leaks occur much less often. Java also has a rich library set, so that Java is not just syntax of language critical applications.
(3) Cross-platform: Java runs on any platform. There is a Java Virtual Machine (JVM) for all platforms. Vendors provide support for their application servers across all the platforms most of the time. This means that EJB applications could be deployed on all these platforms. This is valuable for customers who have invested in a variety of hardware platforms, such as Intel/AMD X32-X64, SPARC, and mainframes, as well as operating systems including various flavors of UNIX, Windows, and so on, in there -i data centers.
What kind of problems is EJB suitable for?
Specifically, EJB is used to help write logic that solves business problems. Typically,
EJB components (enterprise beans) can perform any of the following tasks:-
(1) Perform business logic: Examples include computing taxes on a shopping cart, ensuring that the manager has authority to approve the purchase order, or sending an order confirmation e-mail using the JavaMail API.
(2) Access a database: Examples include submitting an order for books, transferring money between two bank accounts, or calling a stored procedure to retrieve a helpdesk ticket in a customer service application. Enterprise beans can achieve database access using. many techniques, one of which is Java Database Connectivity (JDBC) API.
(3) Integrate with other systems: Examples include calling a highly transactional CICS legacy system written in C that computes the risk exposure for a new insurance customer, using a legacy VSAM (Virtual Storage Access Method) data store, or accessing SAP R/ 3. Enterprise beans can be integrated with other applications in multiple ways, one of which is the Java EE Connector Architecture.
Give three examples of EJB clients.
- Application clients: Application clients execute on a user’s desktop either within an Internet browser environment as an applet or alone. They connect through the network to EJB components that live on a server.
- Dynamically generated Web pages
- Web service clients
How is distributed computing said to be the foundation of EJB? Elaborate.
EJB enables the development and deployment of distributed components. A distributed component also referred to as a distributed object or remote object is callable from a remote system, i.e. not only it can be called from an in-process client but also from an out-of-process client that\might be located on a different system of the network. A remote invocation of a method on a distributed object follows a common process that is similar across all distributed component technologies. The main steps involved in this remote invocation process are:-
(1) The client calls a stub, which is a client-side proxy object. This stub is responsible for masking network communications from the client.
(2) The stub calls over the network to a skeleton, which is a server-side proxy object. The skeleton masks network communications from the distributed object.
(3) The skeleton delegates the call to the appropriate implementation object. This object serves the call and does the work, and returns control to the skeleton, which returns it to the stub, which finally returns control to the client.
Figure 7 depicts the method of invocation on a remote object. The key point here is that both the stub and the server-side implementation object implement the same interface (called the remote interface).
Enumerate the EJB middleware services.
EJB performs the middleware services in two ways, viz. implicitly and explicitly. We shall not go into the details of these but just enumerate the basic EJB middleware services as:-
- Transaction management
Explain the role-based EJB application life cycle.
An EJB application life cycle involves three phases:-
Depending upon the size and scale of the application, the activities related to each of these phases/roles can range from simple to complex. EJB role-based development is elaborated in Figure 8.
We now briefly touch upon the responsibilities handled by these roles. The bean provider supplies business components, or enterprise answer: The application assembler is the overall application architect. After the application assembler builds the application, the application must be deployed (and go into production) in a running operational environment. This is the responsibility of an EJB deployer. Once the deployment goes live, the ‘system administrator’ takes over to oversee the stability of the operational solution.
Elucidate an EJB container.
An EJB container is a piece of software that implements the EJB specification. The reason for being called a container is that it provides an environment within which EJB components live and breathe. In other words, it provides containment to the EJB components.
An EJB container is responsible for managing your enterprise bean. The most important responsibility of the container is to provide a secure, transactional, distributed environment in which enterprise beans can execute. Enumerated in the following list are just a few of the many services that are made available by the bean container:-
- Transaction management
- Resource and life cycle management
- Remote accessibility
- Support for concurrent requests
- Clustering and load-balancing
What do you mean by isolation levels? Enumerate the various levels of isolation.
Isolation level can be defined as the degree to which operations on data by a certain transaction are affected by concurrent transactions, i.e. other transactions running at the same time. It also implies the degree to which operations on data by a transaction can affect data in concurrent transactions.
The various levels of isolations are enumerated as under:-
(1) Dirty Reads: A dirty read will occur when the first transaction reads uncommitted changes made by a second transaction. If the second transaction is rolled back, the data read by the first transaction would be invalid because the rollback reverses the changes. The first transaction won’t be aware that the data it has read has become invalid.
(2) Repeatable Reads: A repeatable read occurs when the data is guaranteed to look the same if read again during the same transaction. Repeatable reads can be guaranteed in one of two ways – either the data read is locked against changes or the data read is a snapshot that doesn’t reflect changes. If the data is locked, then it cannot be changed by any other transaction until the current transaction ends. If the data is a snapshot, then other transactions can change the data, but these changes won’t be seen by this transaction if the read is repeated.
(3) Phantom Reads: Phantom reads occur when new records inserted into the database are detectable by transactions that started prior to the insert. Queries will include records added by other transactions after their transaction has started.
What do you mean by Heuristic decisions? Elaborate in brief.
Transactions are usually controlled by a transaction manager across multiple databases and servers. The transaction manager controls the transaction, based on the results of a poll against the resources (databases and other servers), it decides whether all the updates should be committed or rolled back.
A heuristic decision is when one of the resources makes a decision to commit or rollback by itself, without permission from the transaction manager. Once a heuristic decision has been made, the atomicity of the transaction is lost and possible data integrity errors can occur.
Enumerate and explain the various transaction types in EJB.
The various transaction attributes/types are enumerated as under:-
(1) Not Supported: This attribute means that when a method on a bean with this transaction attribute is called, the transaction gets suspended until the method is completed, this means that the transaction scope is not propagated to the Not Supported bean or any of the methods calls it makes. Once the method in the Not Supported bean is done, the original transaction resumes its execution.
(2) Supports: Invoking a bean with this attribute will include it in the current transaction scope, i.e. if the bean or client that invokes the Supports bean is part of a transaction scope, the Supports bean, and all beans accessed by that bean become part of the original transaction. However, the Supports bean doesn’t have to be part of a transaction and can interact with clients and beans that are not included in a transaction scope.
(3) Required: When a bean’s transaction attribute is set as Required, it means that the bean method must be invoked within the scope of a transaction. If the calling client or bean is part of a transaction, the Required bean is automatically included in its original transaction scope. However, if the calling client or bean is not involved in a transaction, the Required bean starts its own new transaction. The new transaction’s scope covers only the Required bean and all beans accessed by that bean. Once the method invoked on the Required bean is done, the new transaction’s scope ends.
(4) Requires New: When a bean’s transaction attribute is set as Requires New, it means that a new transaction is always started. Regardless of whether the calling, client, or bean is part of a transaction, a method with the Requires New attribute begins a new transaction when invoked. If the calling client is already involved in a transaction, that transaction is suspended until the Requires New bean’s method call returns. The new transaction’s scope only covers the Requires New bean and all beans accessed by that bean. Once the method invoked on the Requires New bean is done, the new transaction’s scope ends and the original transaction resumes.
(5) Mandatory: When a bean’s transaction attribute is set to Mandatory, it means that the bean method must always be made part of the transaction scope of the calling client. If the calling client or bean is not part of a transaction, the invocation will fail, throwing a javax. transaction.TransactionRequiredException.
(6) Never (EJB 1.1 only): When a bean’s transaction attribute is set to Never, it means that the bean method must never be invoked within the scope of a transaction. If the calling client or bean is part of a transaction, the Never bean will throw a RemotcException. If, however, the calling client or bean is not involved in a transaction, the Never bean will execute normally without a transaction.
(7) Bean Managed (EJB 1.0 only): When a bean’s transaction attribute is set to Bean Managed, it means that the bean or method doesn’t have its transactional context implicitly managed by the EJB server. Instead, the developer can use the Java Transaction API (JPA) to explicitly manage transactions.
What do you mean by Re-entrant? Elaborate in brief.
The re-entrant element in a deployment descriptor of an EJB declares that the bean either allows loopbacks (re-entrant invocations) or not. This element can have one of the two values – True or False. True implies that the bean allows loopbacks; False implies that the bean throws an exception in case a loopback occurs. Beans are not re-entrant by default. When a bean is declared as re-entrant/it means that a method that is downstream in the sequence of method calls will call back the bean. This is not advisable.
How can you commit transactions over multiple databases?
A protocol called a 2-phase commit is used. This will commit the transaction only after updates have gone through on all the different database instances;
Elucidate the different types of beans.
Enterprise JavaBeans are categorized into various types. Depending on the design requirements, you can use the suitable bean type:-
(1) Session beans: Session beans model business processes. They are like verbs because they perform actions. The action could be anything such as adding numbers, accessing a database, calling a legacy system, or calling another enterprise answer: Examples include a pricing engine, a workflow engine, a catalog service, a credit card authorization service, or a stock-trading service. Session beans are further divided into two categories – stateful session beans and stateless session answers: As their names suggest, stateful session hearts maintain state, encapsulated within the bean instance, across multiple; client requests, whereas stateless session beans are not tasked with retaining the state across multiple client requests.
(2) Message-driven beans (MDBs): Message-driven beans are similar to session beans in that they perform actions. The difference is that you can call message-driven beans only implicitly by sending messages to those beans, i.e. there is no direct way of invoking a method on the message-driven bean. Examples of MDBS include beans that, receive’, stock trade messages such as trade acknowledgment messages, credit cm! authorization messages, or messages within a given workflow or a business process where interactions are loosely coupled. These MDBs can, in turn, call the invoked methods directly on other EJBs or indirectly by sending a message to be received by another MDB.
(3) Entity beans: Entity beans model business data. They are like nouns because they are data objects, that is, Java objects that cache database information. Examples include a product, an order, an employee, a credit card, or a stock.
Note: Session beans can harness entity beans to accomplish business transactions.
Illustrate Lifecycle Diagrams of Session Beans.
What does JNDI stand for?
JNDI stands for Java Naming and Directory Interface.
What does POJO stand for?
POJO stands for Plain Old Java Object. As a matter of fact, EJB 3 .0 entities are, in fact, POJOs. ‘
What does JAAS stand for?
JAAS stands for Java Authentication and Authorization Service.
JAAS is a portable interface that enables you to authenticate and authorize users in Java. In a nutshell, it allows you to log in to a system without knowing about the underlying security system being used. Behind the scenes in JAAS, the implementation (such as an application server) then determines if your credentials are authentic. Moreover, JAAS enables you to write your own customized authentication modules that can then be plugged in without the need to change client code.
What would you do to ensure stateful bean recovery in case of its failure? Can a stateless bean also die?
Bean failure is an important factor to consider. Since a stateful session bean caches a client conversation in memory, a bean failure may entail losing your conversation. This was not a problem with statelessness – there was no conversation to be lost.
Losing a conversation can have a devastating impact. If you have large conversations that span time, you have lost important work. Here are some of the guidelines you can use while designing your stateful beans to enable them to handle stateful recovery:-
- Keep your conversations short;
- If the performance is feasible, consider checkpointing stateful conversations yourself to minimize the impact of bean failure (such as by using entities);
- Write smart client code that anticipates a bean failure and reestablishes the conversational state with afresh stateful session bean.
What is an entity? Elaborate.
In multi-tier enterprise applications, you will find typically two different kinds of objects:-
(1) Application logic components: These components provide methods that perform common tasks which might include the following:
- Computing the price of an order
- Billing a customer’s credit card
- Computing the inverse of a matrix
Session beans model these application logic components very well.
(2) Persistent data objects: These are objects that can be rendered into persistent storage by a persistent mechanism. These kinds of objects represent ‘data’ – simple/complex information that you would like saved. Examples in this case include:
- Bank account information, such as account numbers and balance O Human resources data, such as names, departments, and salaries of employees
- Lead-tracking information, such as names, addresses, and phone numbers of prospective customers that you want to keep track of overtime
You may note that these objects represent people, places, and things (they are nouns). They are well suited to handling long-lived business data. Such persistent objects are called ‘entities’ in the new Java specification. These entities are plain old Java objects (POJOs) that are persisted in durable storage such as a database or legacy system. As elaborated above, entities store data as fields such as bank account numbers and bank account balances. They also have methods associated with them such as get account number( ) and get balance( ).
Distinguish between entities and session beans.
The big differences between entities and session beans are that:-
- Entities have a client-visible, persistent ‘identity (the primary key) that is distinct from their object reference;
- Entities have a persistent client-visible state;
- Entities are not remotely accessible;
- An entity’s lifetime may be completely independent of an application’s lifetime.
In fact, entities are in-memory Java representations of persistent data that:
- Is loaded from storage and has its field populated with the stored data;
- Can be modified in-memory to change the values of data;
- Can be saved back, thus updating the database data,
Elucidate the Entity Life-Cycle.
The life of an entity instance has two main aspects: its relationship to a specific persistence context and the synchronization of its state with the database. The EntityManagex (the Entity Manager is the interface that lets you access the entities in your application’s persistence context) distinguishes between four states in the life cycle of an entity (Figure 10 shows these four states and the transitions between them as EntityManager operations are called):-
1. new: The entity instance was created in memory but is not yet associated with either a
persistent identity in the database or a persistence context. Changes in the entity state are not synchronized with, the database at this stage.
2. managed: The entity has a persistent identity in the database and is currently associated with a persistent context. Changes to the identity will be synchronized with the database when transactions are committed or when synchronization is explicitly triggered using the flush( ) operation.
3. detached: The identity does have a persistent identity but is not or is no longer associated
with the persistence context.
4. removed: The identity is currently associated with a persistence context but has been scheduled for removal from the database.
What are Java RMI-IIOP and JNDI in the context of EJB?
EJB depends upon Java RMI-IIOP and JNDI. While RMI-IIOP is the networking protocol used in EJB and is a must for interoperability with non-EJB applications such as legacy applications written in C++ or COBOL, JNDI is how beans (and their clients) lookup other beans and external resources by name when dependency injection is not available or is insufficient.
Elucidate Java RMI-IIOP.
Java RMI (which stands for Java Remote Method Invocation) is a mechanism for performing simple but powerful networking. Using RMI, you can write distributed objects in Java, enabling objects to communicate in memory, across Java virtual Machines and physical devices. Java RMI-IIOP (which stands for Java RMI over the Internet Inter-ORB Protocol) is J2EE’s de facto mechanism for providing networking services relying on the CORBA network protocol IIOP. The main advantage of HOP over plain RMI’s native transport protocol JRMP (Java Remote Method Protocol) is that HOP lets your code interoperate remotely with any application on any platform that uses CORBA (Common Request Broker Architecture). It is also more mature than JRMP.
Elucidate RPC and RMI. How does RMI score over RPC?
A Remote Procedure Call (RPC) is a procedural invocation from a process on one machine to a process on another machine. RPCs enable traditional procedures to reside on multiple machines yet still remain in communication. They provide a simple way to perform cross-process or cross-machine networking.
A Remote Method Invocation (RMI) in Java takes the RPC concept one step further and allows for distributed ‘object’ communications. RMI enables you to invoke not procedures, but methods, on objects remotely. You can build your networked code as full objects. This yields the benefits of object-oriented programmings, such as inheritance, encapsulation, and polymorphism.
The Java’Naming and Directory Interface (JNDI) is a Java API that provides a standard interface for locating users, machines, networks, objects, and services by name, e.g. you can use JNDI to locate a printer on your corporate intranet. You can also use it to locate a Java object or a database. JNDI is used in EJB, RMI-IIOP, JDBC, and more. It is the standard Java way of looking up things by name over the network and is also used to manage an enterprise bean’s environment.
What do you understand by a naming service? Explain giving a suitable example.
To understand JNDI, you must first get familiar with a naming service. A naming service is an entity that performs the following tasks:-
(1) It associates names with objects: We call this ‘binding’ names to objects. This is similar to • a telephone company’s associating a person’s name with a specific residence’s telephone number.
(2) It provides a facility to find an object based on a name: We call this looking up an object, or ‘resolving’ a name. This is similar to a telephone operator finding a person’s telephone number based on that person’s name.
Naming services are everywhere in computing. When you want to locate a machine on a network, the Domain Name System (DNS) is used to translate a machine name to an IP ^Internet Protocol) address.
Explain the underlying need for using JNDI.
JNDI is a system for Java-based clients to interact with naming and directory systems. JNDI is a ‘bridge’ over naming and directory services, a beast that provides one common interface to disparate directories. All directory operations are done through the JNDI interface, providing a common framework. The following surveys the advantages that JNDI has to offer:-
- You need to learn only a single API to access all sorts of directory service information such as security credentials, phone numbers, electronic and postal mail addresses, application preferences, network addresses, machine configurations, and more.
- JNDI insulates the application from protocol and implementation details.
- You can use JNDI to read and write whole Java objects from directories.
- You can link different types of directories, such as an LDAP directory with an NDS directory, and have the combination appear to be one large, federated directory. The federated directory appears to the client to be one contiguous directory.
In J2EE, you can use JNDI for many purposes inclusive of the following:-
- Using JNDI to acquire a reference to the Java Transaction API (JTA) User-Transaction interface;
- Using JNDI to connect to resource factories, such as JDBC drivers or Java Message Service (JMS) drivers;
- Using JNDI for clients and for beans to look up other beans.
List at least four JNDI operations.
After acquiring the initial context, you could begin to execute JNDI operations such as reading or writing data to and from the JNDI tree by using the other API calls available in JNDI. Here is a brief list of available operations that you can call on the context (although only four operations have been asked for, I am giving the complete list; you can choose any four):-
1. list( ) retrieves a list of bindings available in the current context;
2. lookup( ) resolves a name binding in the context, meaning that the operation returns the object bound to a given name in the context;
3. rename( ) gives a context a new name, such as renaming c:\temp to c:\tmp;
4. create subcontexts( ) creates a subcontext from the current context, such as creating c:\foo\bar from the folder c:\foo;
5. destroys context( ) destroys a subcontext from the current context, such as destroying c:foo\bar
from the folder c:\foo;
6. bind( ) creates a new name binding in the current context;
7. rebind( ) is the same operation as bind( ) except that it forces a bind even if there is already something in the JNDI tree with the same name.
How are annotations useful for EJB?
For EJBs, annotations are an alternative to the sometimes tedious and error-prone task of specifying the required metadata in XML descriptor files. The most prominent example of this technique is the popular Xdoclet tool that can, for example, be used to generate EJB deployment descriptor files in XML from EJB-specific source code comments provided by developers. The main point to remember about the Javadoc/Xdoclet approach is that the metadata is placed in comments. This means that it is not processed by the Java compiler.
Outline the pros and cons of Java annotations.
The metadata facility in Java defines an annotation language that is part of the language itself. This has the following advantages when compared with the Xdoclet approach:-
1. Ease of use: Annotations are checked and compiled by the Java language compiler, so no external tool is required.
2. Portability: Because the metadata facility is standardized, annotations are as portable as the rest of the code.
3. Type Checking: Annotations are instances of ‘annotation types’, which are compiled in their own class files.
4. Runtime Reflection: Annotations on a class can be kept in a class file and retained for runtime access.
However, the Java annotation facility in its current form also has its shortcomings
5. Unlike interface classes and exceptions, annotation types cannot form an inheritance hierarchy.
6. Annotation member types are restricted to primitive types, String, Class, enum types, annotation types, and arrays of the preceding types.
7. To annotate ‘existing’ code, you must have access to the source code.
8. Many developers have expressed their dislike of a syntax that leads to source code cluttered with @-signs. Of course, it is a matter of taste.
The above problem mentioned the more general criticism. What about the pros and cons of annotations with regard to EJBs?
From the EJBs point of view, the following are the pros of annotations:-
- Keeping the code and the metadata that describes it in sync is much easier with annotations directly on the source code;
- Compile-time checking on typed source code annotations helps you catch errors earlier than the XML compiler because it cannot detect semantic mismatches with the Java code. This must be checked by additional verifiers at or before deployment time.
As for the cons, the one main argument against using annotations for EJBs is the following:-
To work with the metadata for beans that you didn’t write yourself, you would still need access to the source code. Adding metadata to beans that come in an EJB-jar file without code is not going to work well unless you are allowed to disassemble the code, which is usually not much fun. Fortunately, the EJB specification defines how annotations and XML descriptors can be ‘combined’: the specification requires that containers give descriptor files precedence over source code annotations.
Thus, you can always overrule and redefine the metadata that comes embedded in a far file. In a process that requires different individuals to incrementally modify metadata, you should still consider using external XML descriptor files rather than annotations embedded in the source code.