EJB Interview Questions

February 13, 2009

EJB, Interview Questions

«»

76. How do I implement a logging system in my beans?

 Using java.io is prohibited Using the java.io package from within a bean is prohibited. The EJB 1.1 Specification, section 18.1.2 (Programming Restrictions) states the following:  An enterprise bean must not use the java.io package to attempt to access files and directories in the file system. The file system APIs are not well-suited for business components to access data. Business components should use a resource manager API, such as JDBC API, to store data. Alternative Solutions To perform logging operations you must you a resource connection supported by the EJB programming model. EJB servers may support several resource connection options, which can be used to log events as shown below: · JDBC (javax.sql.DataSource) : Write log events in to a relational database. · URL (java.net.URL) : Write log events to a custom logging server or post them to a web server. · JavaMail (javax.mail.Session) : E-mail log events to a special account · JMS (javax.jms.QueueConnectionFactory | javax.jms.TopicConnectionFactory) : Send the log events as messages. 

77. What is a container?

Enterprise beans are software components that run in a special environment called an EJB container. The container hosts and manages an enterprise bean in the same manner that a Java WebServer hosts a Servlet or an HTML browser hosts a Java applet. An enterprise bean cannot function outside of an EJB container. The EJB container manages every aspect of an enterprise bean at run time including remote access to the bean, security, persistence, transactions, concurrency, and access to and pooling of resources.

The container isolates the enterprise bean from direct access by client applications. When a client application invokes a remote method on an enterprise bean, the container first intercepts the invocation to ensure persistence, transactions, and security are applied properly to every operation a client performs on the bean. The container manages security, transactions, and persistence automatically for the bean, so the bean developer doesn’t have to write this type of logic into the bean code itself. The enterprise bean can focus on encapsulating business rules, while the container takes care of everything else.

Containers will manage many beans simultaneously in the same fashion that a Java WebServer manages many Servlets. To reduce memory consumption and processing, containers pool resources and manage the lifecycles of all the beans very carefully. When a bean is not being used a container will place it in a pool to be reused by another client, or possibly evict it from memory and only bring it back when its needed. Because client applications don’t have direct access to the beans — the container lies between the client and bean — the client application is completely unaware of the containers resource management activities. A bean that is not in use, for example, might be evicted from memory on the server, while its remote reference on the client remains intact. When the client invokes a method on the remote reference, the container simply re-incarnates the bean to service the request. The client application is unaware of the entire process.

An enterprise bean depends on the container for everything it needs. If an enterprise bean needs to access a JDBC connection or another enterprise bean, it does so through the container; if an enterprise bean needs to access the identity of its caller, obtain a reference to itself, or access properties it does so through the container. The enterprise bean interacts with its container through one of three mechanisms: callback methods, the EJBContext interface, or JNDI.

  • Callback Methods: Every bean implements a subtype of the EnterpriseBean interface which defines several methods, called callback methods. Each callback method alerts the bean of a different event in its lifecycle and the container will invoke these methods to notify the bean when it’s about to pool the bean, persist its state to the database, end a transaction, remove the bean from memory, etc. The callback methods give the bean a chance to do some housework immediately before or after some event. Callback methods are discussed in more detail in other sections.
  • EJBContext: Every bean obtains an EJBContext object, which is a reference directly to the container. The EJBContext interface provides methods for interacting with the container so that that bean can request information about its environment like the identity of its client, the status of a transaction, or to obtain remote references to itself.
  • JNDI: Java Naming and Directory Interface is a Java extension API for accessing naming systems like LDAP, NetWare, file systems, etc. Every bean automatically has access to a special naming system called the Environment Naming Context (ENC). The ENC is managed by the container and accessed by beans using JNDI. The JNDI ENC allows a bean to access resources like JDBC connections, other enterprise beans, and properties specific to that bean.

The EJB specification defines a bean-container contract, which includes the mechanisms (callbacks, EJBContext, JNDI ENC) described above as well as a strict set of rules that describe how enterprise beans and their containers will behave at runtime, how security access is checked, transactions are managed, persistence is applied, etc. The bean-container contract is designed to make enterprise beans portable between EJB containers so that enterprise beans can be developed once then run in any EJB container. Vendors like BEA, IBM, and Gemstone sell application servers that include EJB containers. Ideally, any enterprise bean that conforms to the specification should be able to run in any conformant EJB container.

Portability is central to the value that EJB brings to the table. Portability ensures that a bean developed for one container can be migrated to another if another brand offers more performance, features, or savings. Portability also means that the bean developer’s skills can be leveraged across several EJB container brands, providing organizations and developers with better opportunities.

In addition to portability, the simplicity of the EJB programming model makes EJB valuable. Because the container takes care of managing complex tasks like security, transactions, persistence, concurrency and resource management the bean developer is free to focus attention on business rules and a very simple programming model. A simple programming model means that beans can be developed faster without requiring a Ph.D. in distributed objects, transactions and other enterprise systems. EJB brings transaction processing and disributed objects development into the mainstream.

78. What makes a Java class an enterprise bean?

An enterprise bean is composed of many parts, not just a single class. Essentially, an enterprise bean is constructed with a bean class, remote interface, home interface and deployment descriptor. These constituents are discussed below.

  •  A bean class is the implementation class of the bean that defines its business, persistence, and passivation logic. The bean class implements either the javax.ejb.EntityBean or javax.ejb.SessionBean interface and runs inside the EJB container. Instances of the bean class service client request indirectly; instances of the bean class are not visible to the client.
  •  The remote interface defines the business methods that will be visible to the client’s that use the enterprise bean. The remote interface extends the javax.ejb.EJBObject interface and is implemented by a remote (distributed object) reference. Client applications interact with the enterprise bean through its remote interface.
  •  The home interface defines the create, delete (remove), and query methods for an enterprise bean type. The home interface extends the javax.ejb.EJBHome interface and is implemented by a remote (distributed object) reference. The client application will use the home interface to create beans, find existing beans, and remove specific beans.
  •  The deployment descriptor is used to describe the enterprise bean’s runtime behavior to the container. Among other things the deployment descriptor allows the transaction, persistence, and authorization security behavior of a bean to be defined using declarative attributes. This greatly simplifies the programming model when developing beans.

An enterprise bean represents the sum of all these parts (remote, home, bean class, and deployment descriptor) as one component. An enterprise bean is not an enterprise bean if any one of these parts is missing. A change to anyone of these parts — changing even one attribute in the deployment descriptor for example — creates an entirely new enterprise bean.

79. While deploying CMP entity beans, which fields in the bean are container-managed and how are they identified?

Container-managed fields may be specified in the bean’s deployment descriptor. An entity bean, for example, has an XML deployment descriptor containing elements similar to the following:<br/>

 <enterprise-beans> <entity> <description>This entity bean models an audio compact disc.</description> <ejb-name>MusicCDBean</ejb-name> <home>musicstore.MusicCDHome</home> <remote>musicstore.MusicCD</remote> <ejb-class>musicstore.MusicCDBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>musicstore.MusicCDPK</prim-key-class> <reentrant>False</reentrant> <cmp-field><field-name>upc</field-name></cmp-field> <cmp-field><field-name>title</field-name></cmp-field> <cmp-field><field-name>artist</field-name></cmp-field> <cmp-field><field-name>type</field-name></cmp-field> <cmp-field><field-name>price</field-name></cmp-field> </entity> </enterprise-beans> 

In the above deployment descriptor, the container-managed fields are specified to be upc, title, artist, type, and price.

While the deployment descriptor provides information about the container-managed fields for use during deployment, the details of how these fields are mapped into the database (or other persistent storage mechanism) are controlled by the container-specific deployment process itself. To learn more about the container-specific deployment process, you will need to consult your container vendor’s documentation.

80. Does the EJB programming model support inheritance?

Inheritance is supported in EJB in a limited fashion. Enterprise beans are made up of several parts including: a remote interface; a home interface, a bean class (implementation); and a deployment descriptor

The remote interface, which extends javax.ejb.EJBObject can be a subtype or a super-type of remote interfaces of other beans. This is also true of the home interface, which extends javax.ejb.EJBHome. The bean class, which implements either javax.ejb.EntityBean or javax.ejb.SessionBean can also be a subtype or super-type of the bean class used by another enterprise bean. Deployment descriptors are XML files, so there is no Object-Oriented (OO) inheritance in the deployment descriptor.

Because an enterprise bean is not one object — its the composition of several parts — traditional OO inheritance is not possible. The constituent Java parts (remote, home, bean class) of an enterprise bean may themselves subtype or serve as super-type, but the bean as a whole (the sum of its parts) doesn’t support inheritance.

81. How should complex find operations be implemented?

In bean-managed persistence (BMP) complex find operations are not difficult to implement, because you have complete control over how a find operation works through the ejbFind methods in the bean class. ejbFind methods in BMP entities can span multiple tables and even different data sources to locate the right entity beans.

With container-managed persistence (CMP) its more difficult because you are dependent on the versatility of the EJB vendor. In other words, if the vendor does not support sophisticated find operations or syntax, its more difficult to declare complex find operations at deployment time. With CMP you have a couple options:

  • · Convert the CMP bean to a BMP bean and hand code the ejbFind methods yourself. This is a classic scenario for using BMP over CMP; when the EJB vendor is not sophisticated enough to support a bean’s data access needs.
  • · Use a session bean to obtain the data you need. When a search operation becomes to complex to implement in a single bean its a good indication that the search operation is not appropriate for a find method. Search operations that span the data encapsulated by several different entity beans should be placed in a session bean with the emphasis on returning only the data needed, not necessarily bean references. Data can be returned in tabular format instead of bean references.

NOTE:

A common design error is to implement search operations that filter results of multi-entity find requests implemented by other entity beans. This should be avoided. If you can not find the entity beans in one find request, then you should use a search method in a session bean.

82. Can I use Threads in a enterprise bean?

No. The thread management is done by the container for you. As a bean developer you are not allowed to use threads.

Section 18.1.2 of the EJB 1.1 specification states:

  • · The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread; or to change a thread’s priority or name. The enter-prise bean must not attempt to manage thread groups.

These functions are reserved for the EJB Container. Allowing the enterprise bean to manage threads would decrease the Container’s ability to properly manage the runtime environment.

83. Why are beans not allowed to create their own threads?

Enterprise beans exist inside a container at run time. The container is responsible for managing every aspect of the enterprise bean’s life including: transactions, access control, persistence, resource pooling, etc. In order for the container to manage the runtime environment of a bean, it must have complete control over the threads that access and run within a bean. This means that beans can not start or manage their own threads. Containers deny enterprise beans the privilege to manage threads for three basic reasons: Resource management, security, and thread-sensitive storage.

Resource Management

Containers manage every aspect of the runtime environment used by enterprise beans including transactions, access control, life cycle, resource connections, VM security, class loading, and threads. This allows the container to conserve as many resources as possible, which is important when there are hundreds of enterprise beans servicing thousands of clients. Without strict management of resources like memory and threads, EJB systems might consume to many resources (memory and cycles), which would result in a slow system, a prospect that is untenable in a high-transaction environment. Threads started and managed by enterprise beans would not be managed by the container, which would make it difficult to conserve resources.

Security

There is no way for a container system to know in advance that a bean’s use of threads is benign. While intentions may be sincere it is possible — probably inevitable — that developers would create malignant beans that spawn so many threads that the entire system slows down. One bean instance’s misuse of threads or the commutative effect of many instances could cause a system slowdown. This is an insurgent denial of service, where the beans themselves sabotage a system’s ability to respond to client requests. Security is a very good reason for denying bean’s the privilege of starting and managing their own threads.

Thread-Specific Storage

Thread-Specific Storage (TSS) is an established and common technique employed by vendors to propagate and track client requests through the container system. It involves associating data with a thread. The data may be information about the client’s identity, the transaction context, and other information, which can be accessed by any part of the container without having to pass the data explicitly. This is especially useful when enterprise beans invoke other enterprise beans or access resources, because it provides a convenient and transparent mechanism for transferring information about the who is making the request and under what circumstances. Each vendor will use the TSS technique differently according to the mechanics of their server. Threads started and managed by the enterprise bean explicitly would not have the proper TSS — that would require intimate knowledge and access to the vendors container system. Without the right TSS the enterprise bean’s threads can not operate within the container system properly. This is another reason why bean are not allowed to start and manage their own threads, it would short-circuit the vendor’s use of TSS.

84. How does EJB support polymorphism?

Because an EJB consists of multiple “parts”, inheritance is achievable in a rather limited fashion (see FAQ answer on inheritance here). There have been noteworthy suggestions on using multiple inheritance of the remote interface to achieve polymorphism, but the problem of how to share method signatures across whole EJBs remains to be addressed. The following is one solution to achieving polymorphism with Session Beans. It has been tried and tested on WebLogic Apps Server 4.50 with no problems so far.

We will use an example to show how it’s done. Say, there are 2 session beans, Tiger and Lion, that share some method signatures but provide different implementations of the methods.

  • · AnimalHome and Animal are the home and remote interfaces. The signatures of the polymorphic methods are in Animal.
  • · AnimalBean is the base implementation bean.
  • · TigerBean and LionBean extend from AnimalBean. They may override the methods of AnimalBean, implementing different behaviors.
  • · Deploy Tiger and Lion beans, specifying AnimalHome and Animal as their home and remote interfaces. Note that Tiger and Lion should have different JNDI lookup names.

85. What classes does a client application need to access EJB?

It is worthwhile to note that the client never directly interacts with the bean object but interacts with distributed object stubs or proxies that provide a network connection to the EJB container system.

The mechanhism is as follows.

  1. The client uses the JNDI context to get a remote reference (stub) to the home object ( the EJBHome).
  2. It uses the home to get a remote reference (stub) to the EJBs remote object (the EJBObject)
  3. It then invokes business methods on this remote object.

The client needs the remote interface, the home interface, the primary key( if it is an entity bean).

In addition to these, the client would need the JNDI factory implementation, and the remote and home stubs. In some EJB servers the Factory and/or stubs can be dynamically loaded at run time. In other EJB servers they must be in the classpath of the client application.

86. What is an EJB primary key? How is it implemented when the database doesn’t have a primary key?

A primary key is an object that uniquely identifies the entity bean. According to the specification, the primary key must be unique for each entity bean within a container. Hence the bean’s primary key usually maps to the PK in the database (provided its persisted to a database).

You may need to create a primary key in the database for the sake of referential integrity. This does not, however, mean you NEED a primary key in the database. As long as the bean’s primary key (which maps to a column or set of columns) can uniquely identify the bean it should work.

87. What’s an .ear file?

An .ear file is an “Enterprise Archive” file. The file has the same format as a regular .jar file (which is the same as ZIP, incidentally). The .ear file contains everything necessary to deploy an enterprise application on an application server. It contains both the .war (Web Archive) file containing the web component of the application as well as the .jar file. In addition there are some deployment descriptor files in XML.

88. Can beans use stored procedures in a database?

Stored procedures can be used by session beans that access the database using JDBC and bean-managed entity beans that use JDBC to manage their own persistence. JDBC provides a call interface for using stored procedures. An example is provided below:

 InitialContext cntx = new InitialContext( ); DataSource dataSource = (DataSource) cntx.lookup("java:comp/env/jdbc/mydatabase"); Connection con = dataSource.getConnection( ); CallableStatement storedProcedure = con.prepareCall("{? = call someprocedure [(?,?)]}"); 

89. Is method overloading allowed in EJB?

Yes you can overload methods.

90. How can JMS be used from EJB 1.1?

The same as any client would use JMS. At this point there is no integration, but it is planned for a future release of the EJB spec.

91. Can primary keys contain more than one field?

Yes, a primary key can have as many fields as the developer feels is necessary, just make sure that each field you specify as the primary key, you also specify a matching field in the bean class. A primary key is simply one or more attributes which uniquely identify a specific element in a database. Also, remember to account for all fields in the equals() and hashCode() methods.

92. How does Container Managed Persistence work with automatically generated database ID fields? Should I map the ID field explicitly or leave it unspecified?

In the Deployment Descriptor, map the normal fields appropriately, but don’t specify the auto-id field as one of the container managed fields.

93. Let’s assume I use a JavaBean as a go-between a JSP and an EJB, and have, say, 50 concurrent clients that need to access the EJB functionality. Will the JSP container actually instantiate 50 instances of the bean, or can it reuse a single instance to access the EJB?

  • It depends on the scope you associate with the JavaBean. If you assign the bean with page (which is the default) scope or request scope, a new bean will be instantiated for each incoming request.
  • If you assign the bean with session scope, you will still have 50 instances loaded in memory (assuming each incoming request is triggered by a distinct client), although some may have been instantiated from an earlier request from the same client. However, you may not want to use the session scope for a high-volume site as these beans will continue to reside in memory, long after the request has been serviced, consuming valuable resources until they are invalidated either explicitly or due to a session timeout.
  • You can also assign the bean with application scope, in which case it is instantiated just once before being placed into the servlet context of the container. It can then be accessed at a later time, as long as the server is up and running. Although this may sound like an attractive proposition, do note that you will have to contend with significant multithreading issues. For instance, you’ll have to ensure that the bean is accessed in a thread-safe manner from each of the JSP files. While you can do this using explicit synchronization from within the JSP file, do note that your application may take a significant performance hit because of this – especially if you expect tens or hundreds of concurrent clients accessing your pages.
  • So, in short, your best bet may be to assign the bean with request scope.

94. What happens when two users access an Entity Bean concurrently?

Taken from Enterprise JavaBeans by Richard Monson-Haefel, “EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the EJB object, no other client can access that bean instance until the method invocation is complete.”

So, to answer your question, two users will never access an Entity Bean concurrently.

95. What’s the reason for having two interfaces — EJBHome for creating, finding & removing and EJBObject for implementing business methods. Why not have an single interface which supports both areas of functionality?

This design reflects the common “Factory” Design pattern. The EJBHome interface is the Factory that creates EJBObjects. EJBObject instances are the product of the factory. The reason for having two interfaces is because they are both responsible for different tasks. The EJBHome is responsible for creating and finding EJBObjects, whilst the EJBObject is responsible for the functionality of the EJB.

96. Which fields in beans should be public?

All Container Managed Fields in an Entity Bean must be public.

Ejb 1.1 spec section 9.4.1 – “The fields must be defined in the entity bean class as public, and must not be defined as transient.”

97. How do you implement callbacks in EJB?

If your client is an EJB, it can pass a reference to itself to the method of the bean that it is calling. The EJB can then call methods directly on that interface.

If your client is a Java client, your client requires some sort of object that will “listen” for call-backs. This could be either a CORBA or RMI object. Again, you could pass references to these objects to the EJB, which could then invoke methods on the references.

98. When should I use bean-managed transactions instead of specifying transaction information in the deployment descriptor?

The Sun J2EE EJB Guide says like this:

  • Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your session bean difficult, you should consider using bean-managed transactions.
  • The following pseudo-code illustrates the kind of fine-grained control you can obtain with bean-managed transactions. By checking various conditions, the pseudo-code decides whether to start and stop different transactions within the business method.
 begin transaction ... update table-a ... if (condition-x) commit transaction else if (condition-y) update table-b commit transaction else rollback transaction begin transaction update table-c commit transaction ... 

I think what it means is there are some limitations in j2ee transaction support. In a container managed situation, nested or multiple transactions are not allowed within a method. if a biz method needs those features you need to go for bean managed transactions.

99. How do I automatically generate primary keys?

A common way to do it is to use a stateless session bean to retrieve the ID that you wish to use as the primary key. This stateless session bean can then execute an Oracle sequencer or procedure etc. to retrieve the ID value used as the primary key.

100. How is the passivation of Entity beans Managed?

The passivation of Entity beans is managed by the container. To passivate an instance, the container first invokes the ejbStore() method for synchronizing the database with the bean instance, then the container invokes the ejbPassivate() method. It will then return the bean instance back to the pooled state. (Every bean has an instance pool.)

There are two ways for transitioning an entity bean from the ready to the pooled state, by using the ejbPassivate() or ejbRemove() method. The container uses ejbPassivate() to disassociate the bean instance from the entity object identity, and uses ejbRemove() to remove the entity object.

When the instance is put back into the pool, it is no longer associated with an entity object identity. The container can now assign the instance to any entity object within the same entity bean home.

A bean instance in the pool can be removed by using unsetEntityContext().

email

«»

Comments

comments

,