0% found this document useful (0 votes)
52 views17 pages

My Interview Questions

Enterprise bean's method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction. Transaction attributes are declarative, you can easily change them at a later time.

Uploaded by

Goutham Vangara
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views17 pages

My Interview Questions

Enterprise bean's method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction. Transaction attributes are declarative, you can easily change them at a later time.

Uploaded by

Goutham Vangara
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Interview Questions

this document contains interview questions, possible answers , interesting web references and the ebook references and if the question should be accompanied by the implementation details then the corresponding eclipse project is also mentioned 1. What are the different types of the container managed transactions

Transaction Type
Transaction Required

Description

If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method. The Required attribute will work for most transactions. Therefore, you may want to use it as a default, at least in the early phases of development. Because transaction attributes are declarative, you can easily change them at a later time.

Transaction Requires New

If the client is running within a transaction and invokes the enterprise bean's method, the container takes the following steps: 1. Suspends the client's transaction 2. Starts a new transaction 3. Delegates the call to the method 4. Resumes the client's transaction after the method completes If the client is not associated with a transaction, the container starts a new transaction before running the method. You should use the RequiresNew attribute when you want to ensure that the method always runs within a new transaction.

Mandatory

If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container throws the TransactionRequiredException. Use the Mandatory attribute if the enterprise bean's method must use the transaction of the client.

Not Supported

If the client is running within a transaction and invokes the enterprise bean's method, the container suspends the client's transaction before invoking the method. After the method has completed, the container resumes the client's transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Use the NotSupported attribute for methods that don't need transactions. Because transactions involve overhead, this attribute may improve performance.

Supports

If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. Because the transactional behavior of the method may vary, you should use the Supports attribute with caution.

Never

If the client is running within a transaction and invokes the enterprise bean's method, the container throws a RemoteException. If the client is not associated with a transaction, the container does not start a new transaction before running the method.

2. Singleton pattern various appraoches Sources : http://tech.puredanger.com/2007/06/15/double-checked-locking/ a. Double checked locking which will fail due to the following reasons
public class PieChucker { // Singleton instance, lazily initialized private static PieChucker instance; public static PieChucker getInstance() { if(instance == null) { synchronized(PieChucker.class) { if(instance == null) { instance = new PieChucker(); } } } return instance; } // Private as its only constructed by getInstance() private PieChucker() { }

Why it breaks Thread 1 enters getInstance(), sees null on both if checks, and starts constructing the singleton. Thread 2 enters getInstance() and checks the first if check. At this point, thread 2 has not yet entered the synchronized block, so has not established a happens-before relationship with Thread 1. It is thus undefined whether Thread 2 will see a fully constructed instance (you got lucky!), a partially constructed instance (probably real bad), or null (causing two singletons to get constructed and breaking the singelton-ness). b. Synchronized locking
// Lazy synchronized locking public class PieChucker { // Singleton instance, lazily initialized private static PieChucker instance; public static PieChucker getInstance() { synchronized(PieChucker.class) { if(instance == null) { instance = new PieChucker(); } } return instance; } }

This is guaranteed to be safe due to the synchronized block, which establishes a happensbefore relationship.

c. Double-checked locking with volatile If you want to avoid the synchronized block, you can actually fix double-checked locking by using volatileon the instance attribute. The getInstance() method requires no change. private static volatile PieChucker instance; Declaring instance volatile basically means that an update of the variable establishes a happens-before relationship. Its kind of like having the readers and writers of the volatile being enclosed in synchronized blocks such that the reader is guaranteed to see the updated, safely published version written by the writer d. Static Initialization
public class PieChucker { // Singleton instance, eagerly initialized private static PieChucker instance = new PieChucker(); public static PieChucker getInstance() { return instance; } }

Static initialization is guaranteed to be thread-safe and no synchronization must be incurred. If your singleton is a candidate for eager initialization, Id recommend using it as its so simple. e. Initialize on demand
public class PieChucker { // Singleton class, lazy initialized private static class InstanceHolder { static PieChucker instance = new PieChucker(); } public static PieChucker getInstance() { return InstanceHolder.instance; } }

If you really want lazy initialization, we can do better! Because static classes are not initialized until needed (and the initialization is guaranteed to be thread-safe), the following idiom is safe and incurs no synchronization (plus, its shorter): f. Cases where Singleton should be used Singleton is used when there is a need to share the global data, To Store the configuration in one object and the Logger is also singleton g. How to avoid singletons, what are the alternatives Can be avoided by having a static lass. Cab be avoided using a factory class and the data can be stored in the factory class and for each of the class created the reference to this object can be passed. Can be avoided using dependency injection

3. Different Thread States

4. Servlet Technology a. What is servlet


The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines lifecycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services. b. What are the servlet Lifecycle events Object Web context Event Initialization and destruction Listener Interface and Event Class

javax.servlet.ServletContextListener and ServletContextEvent javax.servlet.ServletContextAttributeLis tener andServletContextAttributeEvent javax.servlet.http.HttpSessionListener,j avax.servlet.http.HttpSessionActivationL istener, and HttpSessionEvent javax.servlet.http.HttpSessionAttributeL istener and HttpSessionBindingEvent javax.servlet.ServletRequestListener and ServletRequestEvent javax.servlet.ServletRequestAttributeLis tener andServletRequestAttributeEvent

Web context

Attribute added, removed, or replaced

Session

Creation, invalidation, activation, passivation, and timeout

Session

Attribute added, removed, or replaced

Request

A servlet request has started being processed by web components Attribute added, removed, or replaced

Request

c.

Basic Servlet Structure

import java.io.*; import javax.servlet.*;

import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } }

d.

Servelt LifeCycle Methods a. Init -> called by the container b. Service called by the container, which inturn calls the appropriate doget/post methods c. Destroy -> called by the container

e.

Servlet Class Hierarchy

Class Hierarchy
o

java.lang.Object o javax.servlet.http.Cookie (implements java.lang.Cloneable) o java.util.EventObject (implements java.io.Serializable) o javax.servlet.http.HttpSessionEvent o javax.servlet.http.HttpSessionBindingEvent o javax.servlet.ServletContextEvent o javax.servlet.ServletContextAttributeEvent o javax.servlet.ServletRequestEvent o javax.servlet.ServletRequestAttributeEvent o javax.servlet.GenericServlet (implements java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig) o javax.servlet.http.HttpServlet (implements java.io.Serializable) o javax.servlet.http.HttpUtils o java.io.InputStream (implements java.io.Closeable) o javax.servlet.ServletInputStream o java.io.OutputStream (implements java.io.Closeable, java.io.Flushable) o javax.servlet.ServletOutputStream o javax.servlet.ServletRequestWrapper (implements

javax.servlet.ServletRequest) o javax.servlet.http.HttpServletRequestWrapper (imple ments javax.servlet.http.HttpServletRequest) javax.servlet.ServletResponseWrapper (implements javax.servlet.ServletResponse) o javax.servlet.http.HttpServletResponseWrapper (impl ements javax.servlet.http.HttpServletResponse) java.lang.Throwable (implements java.io.Serializable) o java.lang.Exception o javax.servlet.ServletException o javax.servlet.UnavailableException

f.

Servlet Interface hierarchy

Interface Hierarchy
o

o o o o o o o o o o o o

java.util.EventListener o javax.servlet.http.HttpSessionActivationListener o javax.servlet.http.HttpSessionAttributeListener o javax.servlet.http.HttpSessionBindingListener o javax.servlet.http.HttpSessionListener o javax.servlet.ServletContextAttributeListener o javax.servlet.ServletContextListener o javax.servlet.ServletRequestAttributeListener o javax.servlet.ServletRequestListener javax.servlet.Filter javax.servlet.FilterChain javax.servlet.FilterConfig javax.servlet.http.HttpSession javax.servlet.http.HttpSessionContext javax.servlet.RequestDispatcher javax.servlet.Servlet javax.servlet.ServletConfig javax.servlet.ServletContext javax.servlet.ServletRequest o javax.servlet.http.HttpServletRequest javax.servlet.ServletResponse o javax.servlet.http.HttpServletResponse javax.servlet.SingleThreadModel

5.

Why MultiThreaded Servlet and Single Threader EJB a. stateless session bean are stateless with respect to the individual calls made to the bean but when the bean itself is considered , it may contain state information. b. There are however multiple instances of the stateless session bean maintained as a pool c. The state for example Entity Manager is not threadsafe , During a call to stateless session bean the user should have exclusive access to this resource, when the next call comes the caller is expectecd to have exclusive access to this resource as well.

6.

OOPs Concepts

1) What are the core OOP's concepts? Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP's concepts. 2) What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model. 3) What is meant by Encapsulation? Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation. 4) What is meant by Inheritance? Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines "is-a" hierarchy among classes in which one subclass inherits from one or more generalised superclasses. 5) What is meant by Polymorphism? Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class. 7. Primitives Primitives There are 8 primitive data types in java. They are not objects. boolean is 8 bits in size and stores true or false. It's default value is false. 7 7 byte is 8 bit signed integer and stores values in the range of -2 to 2 -1.It's default value is 0. 16 char is 16 bit unsigned integer and stores values in the range of 0 to 2 -1 ie between '\u0000' to '\uffff'. It's default value is '\u0000'. 15 15 short is 16 bit signed integer and stores values in the range of -2 to 2 -1. It's default value is 0. 31 31 int is 32 bit signed integer and stores values in the range of -2 to 2 -1. It's default value is 0. 63 63 long is 64 bit signed integer and stores values in the range of -2 to 2 -1. It's default value is 0l. float stores 32 bit floating point values. It's default value is 0.0f. double stores 64 bit floating point values. It's default value is 0.0d.

8. Difference Between Ejb 3.0 and earlier versions of Ejb 1. Compared to EJB 2.1, EJB 3.0 simplifies the process of creating Enterprise JavaBean applications. 2. The underlying concept of the EJB 3.0 specification centers on a plain old Java object (POJO) programming model that uses Java annotations to capture information that deployment descriptors used to contain. Deployment descriptors are now optional in most cases. 3. EJB 3.0 has introduced a lightweight entity bean persistence mechanism through the Java Persistence API. 4. Session Beans no longer require the Home Interface. 5. Entity Beans no longer require Home or Remote Interfaces. 9. Session bean ,State less Session Bean and Stateful Session bean Session beans are transient and relatively short lived
A client interacts with a session bean by invoking one or more methods defined in the bean. This sequence of method calls we call a session, hence the name session beans. The client can be a webtier client such as a servlet or JSP page, or a standalone Java application program.
package ejb30.session; import javax.ejb.Remote; @Remote public interface TimeService { public String getTime(); }

Note that we have prefixed the interface definition with the @Remote annotation. This indicates to the EJB container that this bean may be invoked by a remote client. By remote, we mean a client that does not reside in the same Java Virtual Machine (JVM) as the container. An interface can also be local as we shall see later in this chapter. A stateless session bean's state spans a single method call.
import javax.ejb.Stateless; @Stateless public class TimeServiceBean implements TimeService { public String getTime() { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt.format("%tr", cal); return fmt.toString(); } } JNDI should be used when we are invoking a remote beann if we are invoking local bean then we can use ejb3.0. Stateless Sessione bean Life Cycle The lifecycle is controlled by the container

Stateful Session Bean

In contrast to stateless session beans, stateful session beans maintain state for an individual client over one or more method requests. A stateful session bean is not shared among clients, and a client's reference to a bean only ends when the client ends the session or the session times out. The state is not written to a database but held in the containers cache and is lost when the container crashes.

The bean can provide a @PrePassivate callback method, which is executed immediately before passivation and a @PostActivate callback method, which is executed immediately after activation. A session bean's state may contain open resources such as open sockets, database or JMS connections that cannot be handled by the container during passivation. In these cases the resource will be closed in the @PrePassivate method and reopened in the @PostActivate method. A bean can move from a method-ready state to a does-not-exist state if a @Remove annotated method is invoked. A bean can also do this if a container configured timeout period has been reached. In either case a @PreDestroy annotated method is first invoked. Remote interface uses the RMI-IIOP protocol for network operations.

10. Servlet Interface Return type void ServletConfig void

Method name init getServletConfig service

Parameters ServletConfig ServletRequest, ServletResponse

Exception ServletException ServletException, IOException

String getServletInfo void destroy 11. Why use Servlets when you can do the samething with EJBs
Actually, servlets/JSPs and EJB are complementary, not competing technologies: Servlets provide support for writing web based applications whereas EJBs provide support for writing transactional objects. In larger web systems that require scalability, servlet and JSP or XML/XSL technologies provide support for the front end (UI, client) code, where EJB provides support for the back end (database connection pooling, declaritive transactions, declaritive security, standardized parameterization...) The most significant difference between a web application using only servlets and one using servlets with EJBs is that the EJB model mandates a separation between display and business logic. This is generally considered a Good Thing in non-trivial applications because it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a logical separation for work, and allows the business logic to be tested separately from the UI (among others). Some of the hings that servlets and JSPs can do that EJBs cannot are: Respond to http/https protocol requests. (With JSP) provide an easy way to format HTML output. Easily associate a web user with session information Some of the things that EJBs enable you to do that servlets/JSPs do not are: Declaritively manage transactions. In EJB, you merely specify whether a bean's methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you'll have to write code to manage the transaction, which is difficult if a logical transaction must access multiple datasources. Declaritively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean. In Servlets/JSPs you must write code to do this. Note, however that the security model in EJB is sufficient for only 90% to 95% of application code - there are always security scenarios that require reference to values of an entity, etc. Both Enterprise JavaBeans and Servlets are server side components. What are the major differences between them? Specifically, what is the difference between a Session Bean and a Servlet? Answer: Enterprise JavaBeans are components meant to encapsulate business logic. They do not handle presentation and have a precise set of restrictions they must obey. An EJB may not manage threads, access files with the java.io package, have a GUI, accept socket connections, or load native libraries. These restrictions are imposed because EJBs execute inside an EJB container, roughly analogous to the way servlets execute in a servlet container. Where servlets can be used to perform many arbitrary tasks, including the generation of HTML pages, EJBs are used almost

entirely as business objects. A session bean represents a client for a session or transaction and an entity bean represents a persistent business object that is usually stored in a database. Unlike servlets, a single session bean may exist per client. A single servlet may serve many clients. A session bean usually mediates client access to entity beans, shielding the client from the details of managing state. A very common model is for a servlet to act as a client of a session bean. In this multi-tier model, a user talks to a servlet or JavaServer Page through a Web browser. The servlet manages the session, keeping track of a session bean for each of its clients and forwarding transaction requests to the session bean. The session bean may then access any number of entity beans to do things like lookup customer account data. The session bean executes its business logic and returns results to the servlet which then formats a result for the Web browser. One of the ideas behind EJBs is to componentize server-side business logic and move it closer to the database. EJBs and servlets will typically not run on the same server. A key thing to remember is that both EJBs and servlets must execute inside of a container. For servlets, this is usually a Web server interfaced with a servlet engine. For EJBs, this is an EJB server such as the reference implementation provided with the Java 2 Enterprise Edition SDK.

12. Transaction Isolation Levels ACID is releated to transactions. It is an acronyam of Atomic, Consistent, Isolation and Durable. Transactionmust following the above four properties to be a better one Atomic: It means a transaction must execute all or nothing at all. Consistent: Consistency is a transactional characteristic that must be enforced by both the transactional system and the application developer Isolation: Transaation must be allowed to run itselft without the interference of the other process or transactions. Durable: Durablity means that all the data changes that made by the transaction must be written in some type of physical storage before the transaction is successfully completed. This ensures that transacitons are not lost even if the system crashes. Question: What are the various isolation levels in a transaction and differences between them There are three isolation levels in Transaction. They are 1. Dirty reads 2.Non repeatable reads 3. Phantom reads. Dirrty Reads If transaction A updates a record in database followed by the transaction B reading the record then the transaction A performs a rollback on its update operation, the result that transaction B had read is invalid as it has been rolled back by transaction A. NonRepeatable ReadsIf transaction A reads a record, followed by transaction B updating the same record, then transaction A reads the same record a second time, transaction A has read two different values for the

same record. Phantom ReadsIf transaction A performs a query on the database with a particular search criteria (WHERE clause), followed by transaction B creating new records that satisfy the search criteria, followed by transaction A repeating its query, transaction A sees new, phantom records in the results of the second query. TRANSACTION_READ_UNCOMMITED TRANSACTION_READ_COMMITED=== Avoids dirty read TRANSACTION_REPEATABLE_READ ===Avoids Non repeatable re TRANSACTION_SERIALIZABLE=== Avoids Phontom reads 13 UML

14

Java differences features JDK 1.1 (february 19, 1997) - Retooling of the AWT event model - Inner classes added to the language - JavaBeans - JDBC - RMI J2SE 1.2 (December 8, 1998) playground This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 & version name "J2SE" (Java 2 platform, Standard edition) replaced JDK to distinguish the base platform from J2EE (java 2 platform, enterprise edition) and J2ME (java 2 platform, micro edition). - Strictfp keyword - Reflection - Swing api integration into the core classes - JVM equipped with a jit compiler - Java plug-in - Java IDL - An IDL implementation for corba interoperability - Collections Framework J2SE 1.3 (may 8, 2000) kestrel - Hotspot jvm included - JavaSound - JNDI included in core libraries - Java platform debugger architecture (jpda)

Version Java 1.1

Java 1.2

Java 1.3

Java 1.4

Java 1.5

- RMI was modified to support optional compatibility with corba J2SE 1.4 (february 6, 2002) merlin - assert keyword - Regular expressions - Exception chaining (allows an exception to encapsulate original lower-level exception) - Internet protocol version 6 (IPV6) support - Non-blocking nio (new input/output) - Logging API - Image i/o api for reading and writing images in formats like jpeg and png - Integrated XML parser and XSLT processor (JAXP) - Integrated security and cryptography extensions (JCE, JSSE, JAAS) - Java web start J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5] - Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). - Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. - Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer). - Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). - Swing: new skinnable look and feel, called synth. - Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. - Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact

Java 1.6

through memory. - Automatic stub generation for rmi objects. - Static imports concurrency utilities in package java.util.concurrent. - Scanner class for parsing data from various input streams and buffers. - Assertions - StringBuilder class (in java.lang package) - Annotations Java SE 6 (december 11, 2006) mustang sun replaced the name "J2SE" with java se and dropped the ".0" from the version number. Beta versions were released in february and june 2006, leading up to a final release that occurred on december 11, 2006. The current revision is update 14 which was released in may 2009. - Support for older win9x versions dropped. - Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration - Dramatic performance improvements for the core platform, and swing. - Improved web service support through JAX-WS JDBC 4.0 support - Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically. - Upgrade of JAXB to version 2.0: including integration of a stax parser. - Support for pluggable annotations - Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).

Java se 6 update 10 A major enhancement in terms of end-user usability. - Java Deployment Toolkit, a set of javascript functions to ease the deployment of applets and java web start applications. - Java Kernel, a small installer including only the most commonly used jre classes. Enhanced updater. - Enhanced versioning and pack200 support:

server-side support is no longer required. - Java quick starter, to improve cold start-up time. - Improved performance of java2D graphics primitives on windows, using direct3D and hardware acceleration. - A new Swing look and feel called NIMBUS and based on synth. - Next-generation java plug-in: applets now run in a separate process and support many features of web start applications.

Java se 6 update 12 This release includes the highly anticipated 64-bit java plug-in (for 64-bit browsers only), windows server 2008 support, and performance improvements of java and JAVAFX applications.

You might also like