Thursday, January 17, 2013

EJB in java interview questions....


EJB Interview Question and Answer 

Question1: What do you mean by EJB?

Ans: Most of the time this EJB interview questions is the first questions asked to interviewee, mostly to check how he responds and how its is different than traditional Java beans. Enterprise java bean is a server side component which runs on application server or we call container, developed for the purpose of distributed and enterprise level application .container will provide support for system level services like Transaction Management, security which make developer task easy and he can focus on business logic.


Question 2: What are the different types of EJB?
EJB Interview Question and Answer asked in J2EE InterviewsThis is another beginner level EJB interview questions mostly asked in telephonic interviews and appeared in 2 to 3 years experience level interviews. Mainly three types of EJB, Entity Bean, Session Bean and Message Driven Bean(MDB).

Types of EJB:

Entity Bean: it represents an entity which is mapped with database or we can say it makes OR object Relational mapping with Database. Entity bean typically represent table in RDBMS and each instance represent row in the table.
 Two types of entity bean:

·          CMP Entity bean: Container managed entity bean its responsibility of container to manage the bean persistence behavior.

·          BMP Entity bean: Programmer manage the bean persistence behavior.

Session bean: Session bean is responsible for developing business logic it makes the client server relationship so session beans exist till there is a session exist between client and server, it doesn’t contain persistent business concept.
 Types of session bean

·          Stateless session bean: when there is not need to maintain state of a particular client stateless session bean is used .They alive for short period of time.
       For example if we are validating the credit card we can use stateless session bean.

·          Stateful session bean: stateful session bean maintain the conversational state of client over the series of method call before the bean instance goes to passive state conversational state is saved to persistence area like Hard disk and again when same client send a request and bean instance come into the active state it will come out from hard disk to main memory.
      For Example when we do online banking transaction ,online reservation we use stateful session bean

Message Driven Beans: these beans are work as a listener for messaging services like JMS .



Question 3: Explain the life cycle method of EJB?
One for EJB interview questions which is asked in Junior level interviews. I have not seen this EJB question appeared on more senior level interviews but its good to remember life cycle as here you have chance to show how much EJB you know in depth.

Ans: Life Cycle of Entity Bean:

 First stage is Does Not Exist Stage t hen Container creates the instance of EJB and  call SetEntityContext() method  which will set all entity context to bean and now it will become available on pool ,to get a particular identity of an EJB object it has to move from Pooled stage to ready stage which is done by calling the create () method which in turns call ejbCreate() and ejbPostCreate() method .
There is another way by which directly entity bean can move to pooled stage to ready stage that’s is call ejbActivate() method.now we are ready to invoke the business method of entity bean .After completion of business method if we want to move again in pooled stage from ready stage we can call remove() method which in turns call ejbRemove() or directly call ejbPassivate () method.
At the end container remove the instance of EJBfrom pool and call unSetEntityContext().

Life Cycle of Stateful Session Bean :

Stateful session beans life cycle starts when  client call create() method.The container create the instance of session bean and call setSessionContext() and ejbCreate() method
Now the stateful session bean is ready to serve the client request after serving the request if it is not used after a long time container can move this bean to passive stage by calling the ejbPassivate() method.similarly when bean is in passive stage and client invoke the business method the container call ejbActivate() method to move bean from passive stage to active or ready stage.
At the end of life cycle client  call remove() method and container will call ejbRemove() method and bean is ready for garbage collection.

Life Cycle of Stateless session bean :

Stales session bean has short life cycle it can have two stage does not exist and ready stage. ejb container create the instance of stateless session bean and call setSessionContext () and ejbCreate() method.Now the bean is ready to invoke business method on this.it will not maintain the state so remove () method is been called after completion of business method which in turns  call ejbRemove () and now its ready for garbage collection.
Life cycle of Message Driven bean:

MDBs have same life cycle like stateless session bean. setMessageDrivenContext() method and ejbCreate() method is called by container to create the instance of MDB.now its ready to receive message .and at the end of lifecycle client will call remove () method
which in turns  call ejbRemove () and now its ready for  garbage collection.

Question 4 : can we have static initializer Block in EJB.
This is one of the tricky EJB interview questions which makes you think and some time left you stunned with feeling like “ Ah , I haven’t thought about it”.

Ans .Purpose of Static initializer block is to initialize some static fields before any execution of constructor or method or we can say creation of object. According to EJB Spec it’s a violation if static field are used and they are non final .

“EJB Spec”
Enterprise bean are not allowed to read or write the non final fields. 

But technically,from the point of java its correct but if in EJB we use static initializer block to initialize static field then because EJB components are used in distributed environment mean to say if  single JVM then it will be ok but if run on different JVM then it will be a problem if we change or update the value in on environment then only the instance running on same JVM have new value .that’s why static blocks are avoided and also all static field should be final.
And same thing we can achieve in ejbCreate(), setSessionContext() or setEntityContext() methods.

Question 5: Is threading is possible in EJB?
Another tricky EJB interview question, I love to ask this kind of question because it shows real knowledge of EJB which is important to avoid mistakes while writing enterprise Java application.

Ans: No, Not possible because EJBs are created and managed by container and if in ejbs we allow threading containers life cycle methods will be interrupted by us and also the purpose of EJB is to perform business logic not to controlling a system or implementation level functioning so container will manage the thread and developer can concentrate on business logic.

Question 6: What is connection pooling feature of EJB container?
This EJB interview question is neither tough nor easy, as most of Java programmer familiar with concept of connection pooling that makes it easy but how EJB container does that is something you want to hear from interviewee.

Ans: Connection pooling is one of the Advance feature of container which enhanced our application performance .Using connection pooling mechanism client are not required to create every time connection object to interact with database .Here in pool objects are already available Whenever a client request for a database connection then an instance is picked from the connection pool to get an access to database and when user complete with his work instance is returned to connection pool. There is a limit specified by App server administrator for the availability of number of connections and beyond a specified limit a predefined number increases numbers of connection pool instances. When demand goes back to normal then access amount of connection pool instances are removed.

Question 7: what is Session facade?
This is the most popular interview questions asked in EJB in connection of Session Bean. Session facade not only touch concept of EJB but also it checks design patterns knowledge of interviewee.

Ans: Session Façade is one of the design pattern which is used in EJB component in this pattern session beans are used as a wrapper classes for entity bean and using session bean we interact with Entity bean .it will give clean approach towards client access to bean components and also reduce network calls so as to make the whole system of high performance.  

Question 8:What are the transaction Attribute ?
This kind of EJB questions mostly askedin telephonic interviews but believe me its not easy to answer if you have not really used transaction management feature of EJB. Its easy to mug all these transaction attribute and spill in interview but once interviewer asked cross question you will most likely cripple.

Ans: Transaction is group of operation or work which should be performed either completely or none to maintain the data integrity. All transaction must have ACID property(atomicity ,consistency,integrity,durability) so transaction can be said completed if we commit on successful execution and rollback on unsuccessful execution.
There are two ways of transaction management.
·          Declarative Transaction Mang.
·          Programmatic Transaction Mang.
Now we see what the transactions Attribute are
Transaction Attribute conveys to the container the intended transactional behavior of the associated EJB component's method.

Required: if required attribute is associated with Method then new Transaction context may or may not be created, means if method is already associated with transaction context then no new transaction context should be created.

Requires New: if Requires New attribute is associated with Method then always new Transaction context may be created.

NotSupported:if Method is Associated with this Attribute then method is  a not a part of transaction.

Supported:if a Method is Associated with this transaction Attribute then method will act as Not supported if calling component is not associated with transaction and if calling component is associated with transaction then act as a required Attribute.

Mandatory:if a method is Associated with this attribute then always be called from calling component transaction context.

Never: if a method is Associated with this attribute then never  be called from calling component transaction context.
The default transaction value for EJB is Support.

Question 9:Difference Between ejbStore() and ejbLoad()?
One more popular EJB interview question, not seen though it for some time but still an important questions on EJB to prepare.

Ans:Both of these methods are used in context of entity bean for the purpose of synchronizing the instance variable to corresponding value store in the database. ejbLoad method load or refresh the instance variable from the database and ejbStore method writes variables value back to the database.

Question 10: What is the difference between JNDI context, Initial context, session context and ejb context.
JNDI questions most likely asked in any EJB interview so be prepare for that as well.
Ans:
JNDI context: provides mechanism to lookup resources on network.
 Initial Context: it provides initial context to resources.
Session Context:it has all the information available which is required to session bean     from container.
EjbContext:it contain information which is required to both session and entity bean.

some more questions..
::::::::::::::::::::::::::::::::::::::::::::::::::::::


1. What is EJB?

EJB stands for Enterprise JavaBeans and is widely-adopted server side component architecture for J2EE. It enables rapid development of ission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in.

2. What is session Facade?

Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean.

3. What is EJB role in J2EE?

EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.

4. What is the difference between EJB and Java beans?

EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.

5. What are the key features of the EJB technology?

  1. EJB components are server-side components written entirely in the Java programming language
  2. EJB components contain business logic only – no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.
  3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
  4. EJB components are fully portable across any EJB server and any OS.
  5. EJB architecture is wire-protocol neutral–any protocol can be utilized like IIOP, JRMP, HTTP, DCOM, etc.

6. What are the key benefits of the EJB technology?

  1. Rapid application development
  2. Broad industry adoption
  3. Application portability
  4. Protection of IT investment

7. How many enterprise beans?

There are three kinds of enterprise beans:
  1. session beans,
  2. entity beans, and
  3. message-driven beans.

8. What is message-driven bean?

A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.

9. What are Entity Bean and Session Bean?

Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.

10. How EJB Invocation happens?

Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).

11. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be considering as passed-by-value that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container. The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

12. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.

13. Can the primary key in the entity bean be a Java primitive type such as int?

The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).

14. Can you control when passivation occurs?

The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA Weblogic, provide the ability to tune the container to minimize passivation calls. Taken from the Weblogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the transaction setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).

15. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?

Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Managed. In Container Managed Entity Bean – Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistence storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean – The developer has to specifically make connection, retrieve values, assign them to the objects in the ejbLoad() which will be called by the container when it instantiates a bean object. Similarly in the ejbStore() the container saves the object values back the persistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you don’t need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.

16. What is EJB QL?

EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistence and is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

17. Brief description about local interfaces?

EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

18. What are the special design cares that must be taken when you work with local interfaces?

It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.

19. What happens if remove( ) is never invoked on a session bean?

In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

20. What is the difference between Message Driven Beans and Stateless Session beans?

In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.

21. How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

22. What is an EJB Context?

EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

23. Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB?

Technically yes, spec. compliant NO! – The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

24. Is it legal to have static initializer blocks in EJB?

Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields – which may be illegal in EJB if they are read/write – In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

25. Is it possible to stop the execution of a method before completion in a SessionBean?

Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::EJB3.0 ::::::::::::::::::::::::::::::::::::::::::::::::::::

  1. Which of the beans available in EJB 3 are only called by clients ? 
    Session  and Singleton (EJB 3.1) beans are the ones who encapsulate the business logic which is why it is the only bean which is called by clients. Other beans like MDB and Entity beans are called by session and singleton beans to complete the business requirement.
  2. Why is it so to make the session beans into two parts one with interface and the other as impl to the interface ? Or why session beans should be used through business interface ? ( EJB 3.0 Specific ).
    This approach promotes loose coupling since implementation classes can easily be swapped out without a lot of code changes.But in recent EJB 3.1 specification you don't need to implement a business interface for faster development.
  3. What is business interface ?
    An interface through which a client invokes the bean is called a business interface. There are three types of business interfaces available in EJB 3 : Local, Remote and WebService.
  4. Now  in latest version of EJB the dependency injection is available , Do we still need JNDI lookups for getting the business interface ? 
    Yes, Our so called dependency Injection is actually a wrapper over JNDI lookups. The Injected object is actually JNDI looked up by the container and injected to the desired place. What happens inside, is that the same old JNDI lookup (which is done by the container) for our convenience.
     There are places where you will have to use JNDI lookup , where container is not available. Means that, if the container is not there then how would you get the remote object ? The only answer is JNDI.
  5. What are the criteria for a method to be a life cycle method ? 
    A life cycle method can be of any name and any specifier , a return type void and no argument ex : private void cleanup();
    Appropriate annotation should be used. ex: @PostConstruct, @PreDestory in case of stateless beans and  additional @PrePassivate and @PostActivate for stateful session beans.
    It is not necessary to have a life cycle method declared in the business interfaces.Only implementation in the business implemented classes (ie Bean classes) is required.
    The method should not throw any checked exception.

9 comments:

  1. I am in fact grateful to the holder of this web site who
    has shared this great piece of writing at here.

    Feel free to visit my web page ... fitness 19 home office

    ReplyDelete
  2. Everything is very open with a clear description of the challenges.
    It was really informative. Your website is very helpful. Many
    thanks for sharing!

    Also visit my web blog; vertical jump exercises

    ReplyDelete
  3. Greetings! Very useful advice in this particular article!

    It's the little changes that make the most important changes. Thanks for sharing!

    Look at my weblog - vertical jump workouts

    ReplyDelete
  4. I think the admin of this web site is truly working hard in favor of his web page, for the reason that here every material is quality based stuff.


    My web page ... Doobious.Org

    ReplyDelete
  5. of course like your web site but you have to test the spelling on several of your posts.
    Several of them are rife with spelling issues and I in finding it very bothersome
    to tell the truth however I will definitely
    come back again.

    Also visit my site; workouts for vertical

    ReplyDelete
  6. I am sure this post has touched all the internet
    people, its really really good post on building up new blog.


    Feel free to surf to my site workouts To jump higher

    ReplyDelete
  7. I like the helpful info you provide to your articles. I'll bookmark your blog and check again here regularly. I am rather sure I will be informed plenty of new stuff right here! Good luck for the next!

    my blog: http://ocbrowser.tseaz.com/

    ReplyDelete
  8. This is my first time go to see at here and i am truly impressed to read all at one place.


    my web-site: exercises to improve vertical leap

    ReplyDelete
  9. Fantastic blog you have here but I was wondering if you knew of any forums that cover
    the same topics talked about in this article?
    I'd really love to be a part of group where I can get feed-back from other experienced individuals that share the same interest. If you have any suggestions, please let me know. Many thanks!

    Here is my website charleston bed and breakfast

    ReplyDelete

Creating mirror of BST