The largest Interview Solution Library on the web


Interview Questions
« Previous | 0 | 1 | 2 | 3 | 4 | Next »

61.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.

62.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.

63.. 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

64.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.”

65.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.

66.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.
1.begin transaction ... update table-a ...if(condition-x)
2.commit transactionelseif(condition-y)
3.update table-b commit transactionelserollback
4.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.

67. 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.

68.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().

69.To complete a transaction, which Transaction Attributes or Isolation Level should be used for a stateless session bean?

[For example, I have a method transfer which transfers funds from one account to another account.] Vague question. Is the Session bean doing the DB work? I’ll assume no. Let’s say AtmEJB is a Session bean with the transfer method. Let’s say AccountEJB is an Entity bean.
Step 1: When the client invokes the transfer method you want that to be the transaction; i.e. “the transfer transaction”. therefore you need to set the tx attribute of transfer to something that will make the container start a tx at the beginning of transfer and terminate it at the end of transfer. RequiresNew might be a good choice but you need to look at all your use cases not just this one.
Step 2: The AccountEJB methods invoked from the transfer method need to have a tx attribute that allows them to be part of an ongoing tx. That means that deposit and withdraw cannot be RequiresNew! (that would suspend the transfer tx and run in its own tx). Look at the spec for these: there are 3 that meets the criteria for deposit and withdraw in the transfer use case. Which one to use? What are the other use cases in which deposit and withdraw will be called? Find one that works for each one.

70.Explain the different Transaction Attributes and Isolation Levels with reference to a scenario?

The Enterprise JavaBeans model supports six different transaction rules:

  • TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the enterprise bean manually manages its own transaction control. EJB supports manual transaction demarcation using the Java Transaction API. This is very tricky and should not be attempted without a really good reason.
  • TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the enterprise bean cannot execute within the context of a transaction. If a client (i.e., whatever called the method-either a remote client or another enterprise bean) has a transaction when it calls the enterprise bean, the container suspends the transaction for the duration of the method call.
  • TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean can run with or without a transaction context. If a client has a transaction when it calls the enterprise bean, the method will join the client’s transaction context. If the client does not have a transaction, the method will run without a transaction.
  • TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean must execute within the context of a transaction. If a client has a transaction when it calls the enterprise bean, the method will join the client’s transaction context. If the client does not have a transaction, the container automatically starts a new transaction for the method. Attributes
  • TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the enterprise bean must execute within the context of a new transaction. The container always starts a new transaction for the method. If the client has a transaction when it calls the enterprise bean, the container suspends the client’s transaction for the duration of the method call. TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise bean must always execute within the context of the client’s transaction. If the client does not have a transaction when it calls the enterprise bean, the container throws the TransactionRequired exception and the request fails.

71.What is the most efficient approach for integrating EJB with JSP? Should the EJBs be invoked directly from within JSP scriptlets? Should the access take place from within Java beans? Or is it best to use custom tags for this purpose?

JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in many lines of code on your JSP page, including try…catch blocks to catch naming and finding exceptions.
Using a standard JavaBean as an intermediary between the JSP page and EJB server cuts down on the amount of code needed to add to a JSP page, and promotes reuse. The JavaBean should be a simple wrapper around the EJB you are accessing.
If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB parameters, such as the server URL and server security parameters.
Custom tags are also an option. However, they require a lot more coding than a simple JavaBean wrapper. The point should be to rewrite as little code as possible while at the same time keeping the JSP scriptlet content as light as possible.

72.How do you get a JDBC database registered with a JNDI name so that it can be accessed from an EJB?

The short answer is that it depends on which container you’re using to some extent. The one thing that (should be) common in EJB 1.1 containers is that the ejb-jar.xml file’s entry for that bean needs to contain a ‘resource-ref’ stanza, like so:
1 <resource-ref> <res-ref-name> jdbc/LocalDB2<res-ref-name>
2 <res-type>javax.sql.DataSource<res-type>
3 <res-auth>Container<res-auth> <resource-ref>
The res-ref-name is the most interesting part. This is the JNDI name relative to the java:comp/env namespace. Hence, to get this connection you’d do (in your bean):
1 Context context =newInitialContext();
2 DataSource source = context.lookup("java:comp/env/jdbc/LocalDB2");
which gives you a DataSource that you can call getConnection on. The other half of this is container specific and done at deployment time by a ‘Deployer’ or ‘Assembler’ (to use the rolenames specified by the EJB spec.) This can work very differently from one container to the next, but here are a couple of (abbreviated) examples.
With Weblogic 5.1, you must define a connection pool in weblogic.properties, then edit the weblogic specific deployment descriptor (using the EJB Deployment tool) to associate the resource-ref specified in ejb-jar.xml with that connection pool.
With Inprise Application Server 4.0, all of the parameters for the connection (JDBC driver, connection URL, etc.) are specified in the inprise specific deployment descriptor (also editable via their deployment tool). Other servers will have other ways of associating the resource-ref with a pre-defined connection pool

73.How to manage fields that can have null values in a container-managed Entity bean?

First of all, let’s just set up a typical scenario: You are developing a product which allows a bank to sign up new customers online. You have done analysis and design and settled on having two tables: ‘users’ and ‘account’ (let’s keep it simple). Each “user” will have a corresponding “account”. The foreign key between the two will be the “account number”.
So, for the ‘users’ table, you have the following fields: firstName, lastName, userId, password, and acctNum. When this table is created in the database, it is empty. Now you must relate your EJB code to this table for persistence. For simplicity sake I will leave out the Session bean (which I would use to talk to my Entity bean), the Entity bean primary key class, and the home and remote interfaces. We have the UserBean:
1 publicclassUserBeanimplementsjavax.ejb.EntityBean
2 {publicString firstName =null;publicString lastName =null;
3 publicString userId =null;publicString password =null;
4 publiclongacctNum = -1;/** * Called by the container after the
5 UserHome.create() is called */
6 publicvoidejbCreate(String userId, String password,longacctNum)
7 {this.userId = userId;this.password = password;this.acctNum = acctNum; } ... ...
8 publicvoidsetUserData(UserData data)throwsRemoteExeption, UserDataException
9 {this.firstName = data.getFirstName();
10 this.lastName = data.getLastName(); } ... ... }
Now, assuming you have the User (remote interface class), UserHome (home interface class), UserPK (primary key class) already done, you need to create the bean’s deployment descriptor. Inside the deployment descriptor, you must specify the database table, ‘users’, which this bean will map to. Also, you must specify which fields from your bean map to which fields in the ‘users’ database table. (This is how the container knows which fields to persist between your bean and the database table.) Now assuming all code compiles and you have an EJB server up and running and you have deployed your bean, all you need to do is write a client (I would use a client to access a session bean, say ‘CustomerSession’, which would talk to my entity bean) to create a new user and pass in the userId, password and acctNum values, which will create the new user in the database. Notice the fields in the UserBean will now be set, but the firstName and lastName fields will still be set to null. These fields will still be empty in the database and will not change until these fields are set in the bean, since it is persisted. Now, call the setUserData(UserData data) method for setting the firstName and lastName, and these fields will now be set in the database and no longer be null. The container will handle the persistence of any fields which are set to null, just as it will handle any fields which are set to some meaningful value

74.How can I debug my EJB applications?

This depends upon which EJB Container you are using. Borland’s JBuilder 3.5, Foundation Edition allows you to debug any Java 2 application, including the Inprise Application Server, WebLogic Server and J2EE Reference implementation. You can download it free from www.borland.com/jbuilder.
There are other IDE’s out there including NetBeans/Forte www.sun.com/forte/ffj/ce/ that can also debug EJB.

75.How can an applet talk directly with EJB?

An applet must use the same procedure as any other Java class: it must use JNDI to locate the EJB Home Interface, then use RMI to talk with the Home Interface as well as the EJB itself.
This means that the J2EE and/or JNDI and/or RMI classes need to be present in the applet’s Java Virtual Machine. The easiest way to assure this is to use the latest Java Plug-in. Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have various problems with RMI and JNDI classes that are beyond the scope of this answer.
Note, however, that it is not recommended to use EJB directly from applets, in part due to compatibility issues. Instead, you can use Servlets inside the application server to provide an HTML front-end that is assured to work on a much larger base of clients.

76.What is the best way of implementing a web application that uses JSP, servlet and EJB technologies all together following a Model View Controller (MVC) architecture?

[See the Sun J2EE Blueprints for “an integrated set of documentation and examples that describe and illustrate ‘best practices’ for developing and deploying component-based enterprise applications using the J2EE platform” including some good architecture whitepapers and source code. -Alex] Hmm, ‘Best Way’ is a bit rough – there are several ‘good’ ways, and the usual set of trade-offs between them. (I’m a consultant – I have to start any answer with “It depends…”, otherwise they revoke my whiteboard privileges)
The main thing you need to keep in mind as you design this sort of a system is that you want the interface into the EJB’s to be rather narrow: in any flow, the ideal is to call one EJB method (hopefully on a stateless session bean), and let it make calls to entities on your behalf, then hand back the data you need to display.
How you display it depends: you can either embed beans on your JSPs and let the beans make that hopefully-one EJB call, or you can post to a servlet, let that make the call, then forward to the JSP for display. The second of these is more flexible and gives you more leverage to hide, change, and enforce your site’s structure. The first, however, will be easier for developers new to this web thing to follow.
Essentially, I’m saying that Entity beans are your model, your controller is Session beans (maybe with a bit of help from servlets or beans), and your JSPs, beans and servlets are your View.
One thing to note here: this discussion strongly implies that your EJBs are capable of externalizing their state as some number of very simple ‘value objects’ (not EJBs themselves, just something we can pass back and forth). These value objects are probably tuned tightly to a workflow, and will be produced by that session bean. This way the traffic between the EJB (server) and the JSP/Servlet (client) is tuned to what the client needs, while the transaction load on the server is minimized.

77.When does the container call my bean’s ejbCreate / ejbPostCreate / ejbStore / ejbPassivate / ejbActivate / ejbLoad / ejbPassivate method? And what should I do inside it?

The lifecycle of an enterprise bean is the heart of the EJB system. Your bean is basically implemented as a set of callback methods. There are a lot of these methods, which can be confusing; however, the implementation of each one is actually quite straightforward. Most of the time you can get away with implementing only a few of them.
Using Bean-Managed Persistence, each callback method ejbX means the obvious thing (usually “you must do X”).
Using Container-Managed Persistence,

  • ejbCreate means “fill in your defaults”
  • ejbPostCreate means “your primary key is now valid; keep initializing”
  • ejbStore means “I’m about to store your data into the DB”
  • ejbPassivate means “I just stored your data, and I’m about to passivate you”
  • ejbActivate means “I just activated you, and I’m about to load in your data”
  • ejbLoad means “I just loaded your data from the DB”

78.What’s the difference between EJBHome, EJB Home, EJB Object, EJBObject and EJB (not to mention Home Interface and Remote Interface)?

The EJB spec is all about really bad naming decisions. First, an Enterprise JavaBean is not a JavaBean (but you already knew that). The “Home Interface” is actually a Factory Object. It is responsible for locating or creating instances of the desired bean, and returning remote references.
When you write the source code for the EJB Home Interface, you must extend the interface EJBHome, and provide method signatures for all the desired create() and find() methods. An object that implements the Home Interface is automatically generated by the EJB Server tools.
The “EJB Object”, or Remote Object, is actually a Wrapper. It sits somewhere inside the container, between the client and your code. It is responsible for performing all the setup and shutdown tasks (like opening transactions, or restoring data state) immediately before and after your enterprise bean is called.
The “EJB Object” is generated by the EJB Server tools — you don’t have to write any part of it. However, you do have to write another interface, called the “Remote Interface” or the “EJBObject Interface,” that extends interface EJBObject, and provides method signatures for all the business methods. The server automatically generates a Java class that implements the Remote Interface; it is this object that is registered with RMI, and a reference to it is returned by the Home Interface (which we now know is actually a Factory Object). The “EJB,” or Enterprise Bean, ironically, is not the EJB Object (even though it is an EJB and it is an object). It doesn’t even implement the EJBObject interface, nor does it implement the Remote Interface. Instead, it implements either the EntityBean interface or the SessionBean interface. It also must implement all the methods defined in the Remote Interface — but it doesn’t actually implement the interface (in the Java sense). This is unfortunate, since we cannot rely on the Java compiler to make sure we’ve implemented all the right methods. It must also implement one ejbCreate() method for each create() method in the Home Interface (as well as ejbFind()/find()).

79.Is there a difference between container managed and bean managed persistence in terms of performance?

[Short answer: with bean-managed persistence, you can optimize your queries and improve performance over the generalized container-managed heuristics. But container-managed persistence is very convenient, and vendors will be working to improve its performance as time goes on. -Alex]
There is of course a difference as many CMPs use O-R mapping using metadata, which is slower than hardcoded queries (except vendors like GemStone that use a OODB which is slow anyway!) As always, a lot depends on the database schema. Given that CMP is still evolving, complex relationships (e.g.inheritance) and distributed transactions are not even supported by most EJB server vendors, leave alone performance.
Having said that however, it does not seem right to compare BMP and CMP on performance because the motivation of CMP is precisely to relieve bean providers from thinking about this! In (J2EE) theory, a good CMP implementation should perform well in a production environment; in practice, except for a couple of vendors who have traditionally been strong in persistent storage space (e.g. Persistence Software, GemStone) you will not find great CMP support at this very moment.
BMP offers a tactical approach while CMP is more strategic. Which implies that if you can work-around some (perhaps severe) limitations for near-term, there may be much to gain with CMP as the vendor offering matures.

80.Given that RMI-IIOP does not support distributed garbage collection (unlike RMI-JRMP), do I need to do something explicitly to GC beans, or is it magically handled by the EJB framework?

It is the Containers’ responsibility to handle distributed garbage collection. This is how EJB’s were designed.

« Previous | 0 | 1 | 2 | 3 | 4 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com