Tuesday, May 14, 2013

How do you make a Servlet thread safe?


A typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex.

Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null
interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure

Thread safety:
􀂃 Instance pooling where container maintains a pool of servlets.
􀂃 Sequential processing where new requests will wait while the current request is being processed.


Best practice:

 It is best practice to use multi-threading and stay away from the single threaded model of the
servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in
read-only manner or shared values can be stored in a database table. The single threaded model can adversely
affect performance.


What is the difference between HttpServlet and GenericServlet?


GenericServlet:
A GenericServlet has a service() method to
handle requests

Protocol independent.

HttpServlet :

The HttpServlet extends GenericServlet and adds support for HTTP
protocol based methods like doGet(), doPost(), doHead() etc.

Protocol dependent.

What are the ServletContext and ServletConfig objects? What are Servlet environment objects?


ServletConfig :

The ServletConfig parameters are for a particular Servlet.
The parameters are specified in the web.xml (ie
deployment descriptor).

ServletContext :


The ServletContext parameters are specified for the entire Web
application. The parameters are specified in the web.xml (ie
deployment descriptor).

What is the difference between doGet () and doPost () or GET and POST?


doGet ():

The request parameters are transmitted as a query string
appended to the request. Allows browser bookmarks but not
appropriate for transmitting private or sensitive information.
http://MyServer/MyServlet?name=paul
This is a security risk.

GET was originally intended for static resource retrieval.


GET is not appropriate when large amounts of input data are
being transferred.

doPost():


The request parameters are passed with the body of the
request.
More secured.


POST was intended for input data submits where the results
are expected to change.



Explain the directory structure of a WEB application?


In Enterprise section for diagram: J2EE deployment structure and explanation in this section where MyAppsWeb.war is depicting the Web application directory structure. The directory structure of a Web application
consists of two parts:
􀂃 A public resource directory (document root): The document root is where JSP pages, client-side classes
and archives, and static Web resources are stored.
􀂃 A private directory called WEB-INF: which contains following files and directories:
􀂃 web.xml : Web application deployment descriptor.
􀂃 *.tld : Tag library descriptor files.
􀂃 classes : A directory that contains server side classes like servlets, utility classes, JavaBeans etc.
􀂃 lib : A directory where JAR (archive files of tag libraries, utility libraries used by the server side classes)
files are stored.

Explain the life cycle methods of a servlet?


The Web container is responsible for managing the servlet’s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in ready state to service requests from clients. The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool [It is also possible to have a single threaded Servlet. Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.



What are ear, war and jar files? What are J2EE Deployment Descriptors?


ear, war and jar are standard application deployment archive files. Since they are a standard, any application
server (at least in theory) will know how to unpack and deploy them.

An EAR file is a standard JAR file with an “.ear” extension, named from Enterprise ARchive file. A J2EE
application with all of its modules is delivered in EAR file. JAR files can’t have other JAR files. But EAR and WAR (Web ARchive) files can have JAR files.

An EAR file contains all the JARs and WARs belonging to an application. JAR files contain the EJB classes and WAR files contain the Web components (JSPs, static content (HTML, CSS, GIF etc), Servlets etc.).

The J2EE application client's class files are also stored in a JAR file. EARs, JARs, and WARs all contain an XML-based

Deployment Descriptors



A deployment descriptor is an XML based text file with a “.xml” extension that describes a component's
deployment settings. A J2EE application and each of its modules has its own deployment descriptor. Pay attention to elements marked in bold in the sample deployment descriptor files shown below.
􀂃 application.xml: is a standard J2EE deployment descriptor, which includes the following structural
information: EJB jar modules, WEB war modules, etc. Also since EJB jar modules are
packaged as jars the same way dependency libraries like log4j.jar, commonUtil.jar etc are packaged, the
application.xml descriptor will distinguish between these two jar files by explicitly specifying the EJB jar
modules.


What is the difference between a Web server and an application server?

Web Server:


Supports HTTP protocol. When the Web server receives
an HTTP request, it responds with an HTTP response,
such as sending back an HTML page (static content) or
delegates the dynamic response generation to some
other program such as CGI scripts or Servlets or JSPs in
the application server.

Uses various scalability and fault-tolerance techniques.

Application Server:


Exposes business logic and dynamic content to the client
through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.


Exposes business logic and dynamic content to the client
through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.


Why use design patterns in a J2EE application?


􀂃 They have been proven. Patterns reflect the experience and knowledge of developers who have successfully used these patterns in their own work. It lets you leverage the collective experience of the development community.

Example Session facade and value object patterns evolved from performance problems experienced due to
multiple network calls to the EJB tier from the WEB tier. Fast lane reader and Data Access Object patterns
exist for improving database access performance. The flyweight pattern improves application performance
through object reuse (which minimises the overhead such as memory allocation, garbage collection etc).

􀂃 They provide common vocabulary. Patterns provide software designers with a common vocabulary. Ideas
can be conveyed to developers using this common vocabulary and format.

Example Should we use a Data Access Object (DAO)? How about using a Business Delegate? Should we
use Value Objects to reduce network overhead? Etc.

Explain MVC architecture relating to J2EE?


MVC stands for Model-View-Controller architecture. It divides the functionality of displaying and maintaining of the data to minimise the degree of coupling (i.e. promotes loose
coupling) between components.


A model represents the core business logic and state. A model commonly maps to data in the database and will also contain core business logic.
A View renders the contents of a model. A view accesses the data from the model and adds display logic to
present the data.
A Controller acts as the glue between a model and a view. A controller delegates the request to the model for application logic and state and also centralises the logic for dispatching the request to the next view based on the input parameters from the client and the application state. A controller also decouples JSP pages and the Servlet by handling the view selection.

Explain MVC architecture relating to J2EE?


MVC stands for Model-View-Controller architecture. It divides the functionality of displaying and maintaining of the data to minimise the degree of coupling (i.e. promotes loose
coupling) between components.


A model represents the core business logic and state. A model commonly maps to data in the database and will also contain core business logic.
A View renders the contents of a model. A view accesses the data from the model and adds display logic to
present the data.
A Controller acts as the glue between a model and a view. A controller delegates the request to the model for application logic and state and also centralises the logic for dispatching the request to the next view based on the input parameters from the client and the application state. A controller also decouples JSP pages and the Servlet by handling the view selection.

Did you have to use any design patterns in your Java project?


Yes.Strategy,Iterator, Decorator,Visitor,Singleton, Factory,
Command, and MVC in Java section.
Why use design patterns, you may ask (Refer Q5 in Enterprise section). Design patterns are worthy of mention in
your CV and interview. Design patterns have a number of advantages:
􀂃 Capture design experience from the past.
􀂃 Promote reuse without having to reinvent the wheel.
􀂃 Define the system structure better.
􀂃 Provide a common design vocabulary.


Some advice if you are just starting on your design pattern journey:

􀂃 If you are not familiar with UML, now is the time. UML is commonly used to describe patterns in pattern
catalogues, including class diagrams, sequence diagrams etc. (Refer Q106 - Q109 in Enterprise section).
􀂃 When using patterns, it is important to define a naming convention. It will be much easier to manage a project
as it grows to identify exactly what role an object plays with the help of a naming convention e.g.
AccountFacilityBusinessDelegate, AccountFacilityFactory, AccountFacilityValueObject, AccountDecorator,
AccountVisitor, AccountTransferObject (or AccountFacilityVO or AccountTO).
􀂃 Make a list of requirements that you will be addressing and then try to identify relevant patterns that are
applicable.

Why does the JVM crash with a core dump or a Dr.Watson error?


Any problem in pure Java code throws a Java exception or error. Java exceptions or errors will not cause a core dump (on UNIX systems) or a Dr.Watson error (on WIN32systems). Any serious Java problem will result in an OutOfMemoryError thrown by the JVM with the stack trace and consequently JVM will exit. These Java stack traces are very useful for identifying the cause for an abnormal exit of the JVM. So is there a way to know that OutOfMemoryError is about to occur? The Java JDK 1.5 has a package called java.lang.management which has useful JMX beans that we can use to manage the JVM. One of these beans is the MemoryMXBean.

An OutOfMemoryError can be thrown due to one of the following 4 reasons:
􀂃 JVM may have a memory leak due to a bug in its internal heap management implementation. But this is highly unlikely because JVMs are well tested for this.
􀂃 The application may not have enough heap memory allocated for its running. You can allocate more JVM
heap size (with –Xmx parameter to the JVM) or decrease the amount of memory your application takes to
overcome this. To increase the heap space:

Java -Xms1024M -Xmx1024M

Care should be taken not to make the –Xmx value too large because it can slow down your application. The
secret is to make the maximum heap size value the right size.
􀂃 Another not so prevalent cause is the running out of a memory area called the “perm” which sits next to the heap. All the binary code of currently running classes is archived in the “perm” area. The ‘perm’ area is
important if your application or any of the third party jar files you use dynamically generate classes. For
example: “perm” space is consumed when XSLT templates are dynamically compiled into classes, J2EE
application servers, JasperReports, JAXB etc use Java reflection to dynamically generate classes and/or
large amount of classes in your application. To increase perm space:
Java -XX:PermSize=256M -XX:MaxPermSize=256M
􀂃 The fourth and the most common reason is that you may have a memory leak in your application



How would you detect and minimise memory leaks in Java?


In Java memory leaks are caused by poor program design where object references are long lived and the garbage
collector is unable to reclaim those objects.
Detecting memory leaks:
􀂃 Use tools like JProbe, OptimizeIt etc to detect memory leaks.
􀂃 Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on
UNIX systems.
􀂃 Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime
class. Place these calls in your code strategically for pre and post memory recording where you suspect to be
causing memory leaks. An even better approach than a utility class is using dynamic proxies  or Aspect Oriented Programming (AOP) for pre and post memory
recording where you have the control of activating memory measurement only when needed.
in Emerging Technologies/Frameworks section).

Minimising memory leaks:

􀂃 Design applications with an object’s life cycle in mind, instead of relying on the clever features of the JVM.
Letting go of the object’s reference in one’s own class as soon as possible can mitigate memory problems.
Example: myRef = null;
􀂃 Unreachable collection objects can magnify a memory leak problem. In Java it is easy to let go of an entire
collection by setting the root of the collection to null. The garbage collector will reclaim all the objects (unless
some objects are needed elsewhere).
􀂃 Use weak references (Refer Q32 in Java section) if you are the only one using it. The WeakHashMap is a
combination of HashMap and WeakReference. This class can be used for programming problems where you
need to have a HashMap of information, but you would like that information to be garbage collected if you are
the only one referencing it.

􀂃 Free native system resources like AWT frame, files, JNI etc when finished with them. Example: Frame,
Dialog, and Graphics classes require that the method dispose() be called on them when they are no longer
used, to free up the system resources they reserve.

How would you improve performance of a Java application?


􀂃 Pool valuable system resources like threads, database connections, socket connections etc. Emphasise on
reuse of threads from a pool of threads. Creating new threads and discarding them after use can adversely
affect performance. Also consider using multi-threading in your single-threaded applications where possible to enhance performance. Optimze the pool sizes based on system and application specifications and
requirements.
􀂃 Optimize your I/O operations: use buffering  when writing to and reading from
files and/or streams. Avoid writers/readers if you are dealing with only ASCII characters. You can use streams instead, which are faster. Avoid premature flushing of buffers. Also make use of the performance and scalability enhancing features such as non-blocking and asynchronous I/O, mapping of file to memory etc
offered by the NIO (New I/O).
􀂃 Minimize network overheads by retrieving several related items simultaneously in one remote invocation if
possible. Remote method invocations involve a network round-trip, marshalling and unmarshalling of
parameters, which can cause huge performance problems if the remote interface is poorly designed.
􀂃 Establish whether you have a potential memory problem and manage your objects efficiently: remove
references to the short-lived objects from long-lived objects like Java collections etc (Refer Q64 in Java
section) to minimise any potential memory leaks. Also reuse objects where possible. It is cheaper to recycle
objects than creating new objects each time. Avoid creating extra objects unnecessarily. For example use
mutable StringBuffer/StringBuilder classes instead of immutable String objects in computation expensive
loops as discussed in Q17 in Java section. Automatic garbage collection is one of the most highly touted
conveniences of Java. However, it comes at a price. Creating and destroying objects occupies a significant
chunk of the JVM's time. Wherever possible, you should look for ways to minimise the number of objects
created in your code:
􀂃 If repeating code within a loop, avoid creating new objects for each iteration. Create objects before
entering the loop (i.e. outside the loop) and reuse them if possible.
􀂃 For complex objects that are used frequently, consider creating a pool of recyclable objects rather than
always instantiating new objects. This adds additional burden on the programmer to manage the pool,
but in select cases can represent an order of magnitude performance gain.
􀂃 Use lazy initialization when you want to distribute the load of creating large amounts of objects. Use lazy
initialization only when there is merit in the design.

Can we use the singleton pattern within our factory pattern code?


When writing your factory class is that, it does not make sense to create a new factory object for each invocation as it is shown in the sample code, which is just fine for the illustration purpose.
ShapeFactory factory = new SimpleShapeFactory();
To overcome this, you can incorporate the singleton design pattern into your factory pattern code. The singleton design pattern will create only a single instance of your SimpleShapeFactory class. Since an abstract factory pattern is unlike factory pattern, where you need to have an instance for each of the two factories (i.e. SimpleShapeFactory and ComplexShapeFactory) returned, you can still incorporate the singleton pattern as an access point and have an instance of a HashMap, store your instances of both factories. Now your calling method uses a static method to get the same instance of your factory, hence conserving memory and promoting object

reuse:
ShapeFactory factory = ShapeFactory. Ge/tFactoryInstance();
factory.getShape();

Why use factory pattern or abstract factory pattern?


Factory pattern returns an instance of several (product
hierarchy) subclasses (like Circle, Square etc), but the calling code is unaware of the actual implementation class.
The calling code invokes the method on the interface (for example Shape) and using polymorphism the correct draw() method gets invoked . So, as you can see, the factory pattern reduces the coupling or the dependencies between the calling code and called objects like Circle, Square etc. This is a very powerful and common feature in many frameworks. You do not have to create a new Circle or a new Square on each invocation as shown in the sample code, which is for the purpose of illustration and simplicity. In future, to conserve memory you can decide to cache objects or reuse objects in your factory with no changes
required to your calling code. You can also load objects in your factory based on attribute(s) read from an external properties file or some other condition. Another benefit going for the factory is that unlike calling constructors directly, factory patterns have more meaningful names like getShape(…), getInstance(…) etc, which may make calling code more clear.

What is a factory pattern?



A Factory method pattern (aka Factory pattern) is a creational pattern. The creational patterns abstract the
object instantiation process by hiding how the objects are created and make the system independent of the object creation process. An Abstract factory pattern is one level of abstraction higher than a factory method pattern, which means it returns the factory classes.


public interface Const {
public static final int SHAPE_CIRCLE =1;
public static final int SHAPE_SQUARE =2;
public static final int SHAPE_HEXAGON =3;
}
public class ShapeFactory {
public abstract Shape getShape(int shapeId);
}
public class SimpleShapeFactory extends
ShapeFactory throws BadShapeException {

public Shape getShape(int shapeTypeId){
Shape shape = null;
if(shapeTypeId == Const.SHAPE_CIRCLE) {
//in future can reuse or cache objects.
shape = new Circle();
}
else if(shapeTypeId == Const.SHAPE_SQUARE) {
//in future can reuse or cache objects
shape = new Square();
}
else throw new BadShapeException
(“ShapeTypeId=”+ shapeTypeId);
return shape;
}
}


Now let’s look at the calling code, which uses the
factory:
ShapeFactory factory = new SimpleShapeFactory();
//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
Shape s = factory.getShape(1);
s.draw(); // circle is drawn
//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
s = factory.getShape(2);
s.draw(); //Square is drawn



Tuesday, May 7, 2013

Not to override HashCode method impact in performance?

A poor hashcode method implementation will lead to collision in HashMap which eventually increase time in adding object in HashMap.

Iterate Over a Map in Java


There are several ways of iterating over a Map in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Mapinterface, following techniques will work for any map implementation (HashMapTreeMap,LinkedHashMapHashtable, etc.)

Method #1: Iterating over entries using For-Each loop.

This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or valuesinstead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}
//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant but it has its own advantages. First of all it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by callingiterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to javadoc.
From performance point of view this method is equal to For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1 but in practice it is pretty slow and inefficient as getting values by a key might be time consuming (this method in different Mapimplementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.

Conclusion

If you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

How to prevent deadlock if N thread access N thread resource without deadlock?

If we acquire resource in particular order and release the resources in reverse order we can prevent deadlock.

Can you override private or static method in Java?

No

Can we throw Runtime Exception in overriding?

Yes we can throw Runtime Exception in Overriding if it is checked exception. checkout rules of method overriding in Java for details.

What will happen if tryied putting key object in HashMap which is already exist?

Tricky question  the answer for same is in HashMap duplicate keys are not allowed.

How does the Object Oriented approach improve software development?


The key benefits are:
􀂃 Re-use of previous work: using implementation inheritance and object composition.
􀂃 Real mapping to the problem domain: Objects map to real world and represent vehicles, customers,
products etc: with encapsulation.
􀂃 Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.


The increased quality and reduced development time are the by-products of the key benefits discussed above.
If 90% of the new application consists of proven existing components then only the remaining 10% of the code have to be tested from scratch.