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.
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.
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:
EJBs offer benefits like transaction management, built-in security features, scalability, and concurrency handling.
The lifecycle of a Stateful Session Bean (SFSB) in EJB includes several stages:
@PostConstruct
annotated method, if present, for initialization.@PrePassivate
annotated method, if present.@PostActivate
annotated method, if present.@PreDestroy
annotated method, if present, before destroying the bean instance.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.
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.
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.
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.
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.
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).
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.
Optimizing performance in EJB applications involves several strategies:
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:
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.
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.
The primary differences between EJB 2.x and EJB 3.x are:
The lifecycle of a Message-Driven Bean (MDB) in EJB includes:
onMessage
method.