Interview

15 EJB Interview Questions and Answers

Prepare for your technical interview with this guide on EJB, covering key concepts and providing insightful questions and answers.

Enterprise JavaBeans (EJB) is a server-side software component that encapsulates business logic of an application. EJB is a crucial part of Java EE (Enterprise Edition) and is widely used for building scalable, robust, and secure enterprise-level applications. It simplifies the development of large-scale distributed systems by providing a set of services such as transaction management, security, and concurrency control, allowing developers to focus on business logic rather than infrastructure concerns.

This article offers a curated selection of EJB-related questions and answers to help you prepare for your upcoming technical interview. By familiarizing yourself with these questions, you will gain a deeper understanding of EJB concepts and be better equipped to demonstrate your expertise to potential employers.

EJB Interview Questions and Answers

1. What is an Enterprise Java Bean (EJB)?

Enterprise Java Beans (EJB) is a specification for building scalable, secure, and transactional enterprise-level applications in Java. EJBs are managed by an EJB container, which is part of a Java EE application server. The container handles services such as lifecycle management, security, transaction management, and concurrency, allowing developers to focus on business logic.

There are three main types of EJBs:

  • Session Beans: These encapsulate business logic and can be stateless, stateful, or singleton.
  • Message-Driven Beans (MDB): These process asynchronous messages from a queue or topic.
  • Entity Beans: These represent persistent data and are typically mapped to a database table, though they are less commonly used today in favor of Java Persistence API (JPA).

EJBs offer benefits like transaction management, built-in security features, scalability, and concurrency handling.

2. Explain the lifecycle of a Stateful Session Bean.

The lifecycle of a Stateful Session Bean (SFSB) in EJB includes several stages:

  • Instantiation: The EJB container creates a new instance of the bean class.
  • Initialization: The container invokes the @PostConstruct annotated method, if present, for initialization.
  • Ready State: The bean can handle client requests, maintaining its conversational state across multiple method calls from the same client.
  • Passivation: If the bean is not in use, the container may passivate it to conserve resources, invoking the @PrePassivate annotated method, if present.
  • Activation: When needed, the container activates the bean, restoring its state and invoking the @PostActivate annotated method, if present.
  • Removal: The container invokes the @PreDestroy annotated method, if present, before destroying the bean instance.

3. What is the role of the @PostConstruct annotation?

The @PostConstruct annotation marks a method to be executed after the bean’s dependencies have been injected. This method is used for initialization tasks before the bean starts processing business logic. It is called once in the bean’s lifecycle, immediately after instantiation and dependency injection.

Example:

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;

@Singleton
public class MyBean {

    @PostConstruct
    public void init() {
        // Initialization code here
        System.out.println("Bean is initialized");
    }

    public void businessMethod() {
        // Business logic here
    }
}

In this example, the init method is annotated with @PostConstruct, meaning it will be called once the MyBean instance is created and its dependencies are injected.

4. Describe how dependency injection works in EJB.

Dependency injection in EJB allows the container to automatically inject dependencies into EJB components using annotations, simplifying code management.

For example, consider a session bean that requires a reference to another session bean. The dependency can be injected using the @EJB annotation:

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class OrderService {

    @EJB
    private InventoryService inventoryService;

    public void placeOrder(Order order) {
        inventoryService.updateInventory(order);
    }
}

In this example, the OrderService bean has a dependency on the InventoryService bean. The @EJB annotation tells the EJB container to inject an instance of InventoryService into the OrderService bean.

5. Write a method that demonstrates the use of the @TransactionAttribute annotation.

The @TransactionAttribute annotation in EJB controls the transactional behavior of enterprise beans. It specifies how the container should manage transactions for a method when invoked. The annotation can take values like REQUIRED, REQUIRES_NEW, MANDATORY, NOT_SUPPORTED, SUPPORTS, and NEVER.

Here is an example demonstrating the use of the @TransactionAttribute annotation:

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

@Stateless
public class TransactionExampleBean {

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void performTransaction() {
        // Business logic that requires a transaction
        System.out.println("Transaction is required for this method.");
    }
}

In this example, the performTransaction method is annotated with @TransactionAttribute(TransactionAttributeType.REQUIRED), indicating it must be executed within a transaction context.

6. What is the role of the @Asynchronous annotation?

The @Asynchronous annotation in EJB allows methods to run asynchronously, meaning the method call returns immediately, and the actual processing happens in a separate thread. This is useful for tasks that are time-consuming and do not need to block the main thread.

Example:

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;

@Stateless
public class EmailService {

    @Asynchronous
    public void sendEmail(String recipient, String message) {
        // Simulate a time-consuming task
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Email sent to " + recipient + " with message: " + message);
    }
}

In this example, the sendEmail method is annotated with @Asynchronous, indicating that it should be executed in a separate thread.

7. Explain the concept of EJB Interceptors.

EJB Interceptors separate cross-cutting concerns from business logic. They can be applied to session beans, message-driven beans, and other interceptors. Interceptors can be defined at the class or method level and can perform tasks before and after a method invocation or lifecycle event.

Example:

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Interceptor
public class LoggingInterceptor {

    @AroundInvoke
    public Object logMethodEntry(InvocationContext ctx) throws Exception {
        System.out.println("Entering method: " + ctx.getMethod().getName());
        try {
            return ctx.proceed();
        } finally {
            System.out.println("Exiting method: " + ctx.getMethod().getName());
        }
    }
}

In this example, the LoggingInterceptor class uses the @AroundInvoke annotation to define a method that will be called before and after the business method it intercepts.

8. What is the difference between container-managed and bean-managed transactions?

In EJB, transactions can be managed in two ways: container-managed transactions (CMT) and bean-managed transactions (BMT).

Container-managed transactions (CMT) are managed by the EJB container, which handles transaction boundaries automatically based on configuration. This approach simplifies development as the developer does not need to write explicit transaction management code.

Bean-managed transactions (BMT) are managed by the bean itself. The developer has full control over transaction boundaries, requiring explicit code to begin, commit, and roll back transactions using the Java Transaction API (JTA).

9. Explain the concept of EJB clustering.

EJB clustering ensures high availability and scalability by grouping multiple servers to work as a single system. This setup allows for load balancing, failover, and improved performance.

In an EJB cluster, multiple instances of an EJB are deployed across different servers. When a client makes a request, it can be handled by any server in the cluster, distributing requests to balance the load. If one server fails, another can take over, providing failover support.

EJB clustering is useful in large-scale applications where availability and performance are important. It allows for horizontal scaling, meaning more servers can be added to handle increased load without significant changes to the application code.

10. How do you optimize performance in EJB applications?

Optimizing performance in EJB applications involves several strategies:

  • Caching: Store frequently accessed data to reduce repeated database queries.
  • Pooling: Configure resource pools for EJB components to manage resources efficiently.
  • Lazy Loading: Implement lazy loading for entity beans to defer loading related data until needed.
  • Efficient Querying: Optimize database queries by using appropriate indexes and selecting only required fields.
  • Transaction Management: Minimize the scope and duration of transactions to reduce locking and improve concurrency.
  • Asynchronous Processing: Offload long-running tasks to asynchronous methods or message-driven beans.
  • Resource Management: Ensure proper management of resources like database connections and JMS connections.
  • Load Balancing: Distribute the load across multiple EJB instances and servers.

11. Explain the concept of EJB Container and its responsibilities.

An EJB Container is a runtime environment provided by a Java EE application server for managing the execution of EJBs. The EJB Container is responsible for services that simplify the development of scalable, transactional, and secure applications.

The primary responsibilities of an EJB Container include:

  • Lifecycle Management: Managing the lifecycle of EJB instances.
  • Security: Providing declarative security.
  • Transaction Management: Handling transaction demarcation.
  • Concurrency Control: Managing concurrent access to EJB instances.
  • Resource Management: Managing resources like database connections.
  • Interceptors: Supporting interceptors for cross-cutting concerns.
  • Dependency Injection: Supporting dependency injection.

12. Describe the role of JNDI in EJB.

JNDI (Java Naming and Directory Interface) provides naming and directory functionality to Java applications. In EJB, JNDI is used to look up EJB components and other resources like data sources and JMS queues.

When an EJB is deployed, it is registered with the JNDI naming service. Clients use this name to look up the EJB reference from the JNDI context.

For example, a client can look up a session bean using the following code:

Context context = new InitialContext();
MyBeanRemote myBean = (MyBeanRemote) context.lookup("java:global/myApp/MyBean");

In this example, the client uses the JNDI name “java:global/myApp/MyBean” to look up the remote interface of the EJB.

13. How does EJB handle concurrency?

EJB handles concurrency through container-managed concurrency (CMC) and bean-managed concurrency (BMC).

1. Container-Managed Concurrency (CMC): The EJB container manages concurrent access to the bean’s methods, ensuring thread safety. For stateless session beans and message-driven beans, the container can create multiple instances to handle concurrent requests.

2. Bean-Managed Concurrency (BMC): The developer manages concurrent access to the bean’s methods, implementing synchronization mechanisms to ensure thread safety. BMC is used when CMC does not meet specific concurrency requirements.

Annotations such as @Lock specify the concurrency management strategy for individual methods. For example, @Lock(LockType.WRITE) ensures only one thread can access the method at a time, while @Lock(LockType.READ) allows multiple threads to access the method concurrently.

14. What are the differences between EJB 2.x and EJB 3.x?

The primary differences between EJB 2.x and EJB 3.x are:

  • Annotations vs. Deployment Descriptors: EJB 3.x uses annotations, simplifying development, while EJB 2.x relies on deployment descriptors.
  • POJO vs. Component Model: EJB 3.x allows the use of POJOs, making development and testing easier, whereas EJB 2.x requires specific interfaces.
  • Dependency Injection: EJB 3.x supports dependency injection, while EJB 2.x requires manual resource lookup.
  • Entity Beans: EJB 3.x replaces entity beans with JPA, which is more efficient. EJB 2.x entity beans are considered outdated.
  • Interceptors: EJB 3.x introduces interceptors for cross-cutting concerns, which EJB 2.x lacks.
  • Lifecycle Callbacks: EJB 3.x provides lifecycle callback methods through annotations, while EJB 2.x requires specific lifecycle interfaces.

15. Describe the lifecycle of a Message-Driven Bean.

The lifecycle of a Message-Driven Bean (MDB) in EJB includes:

  • Creation: The EJB container creates an instance of the MDB.
  • Pooling: MDB instances are placed in a pool, waiting to process incoming messages.
  • Message Handling: When a message arrives, the container selects an instance and invokes the onMessage method.
  • Instance Passivation: The container may passivate an instance to free up resources.
  • Instance Activation: When needed, the container activates the instance.
  • Removal: The container removes the instance when it is no longer needed.
Previous

15 NoSQL Interview Questions and Answers

Back to Interview
Next

15 VB.NET Interview Questions and Answers