Thursday, February 11, 2010
Decorator Pattern
Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains. That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators. This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.
It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.
Example :-A very nice example of decorators is Java's I/O stream implementation.
Wednesday, February 10, 2010
Difference between struts and springs
Question: Difference between Strust and Springs
Answer:Difference between struts and springs could be analysed from various facets.
(1) Purpose of each framework.
(2) Various feature offerings at framework level.
(3) The design & stuff.
Firstly, Struts is a sophisticated framework offering the easy 2 develop, structured view/presentation layer of the MVC applications. Advanced, robust and scalable view framework underpinning reuse and seperation of concerns to certain extent. Springs is a Lightweight Inversion of Control and Aspect Oriented Container Framework. Every work in the last sentence carry the true purpose of the Spring framework. It is just not a framework to integrate / plug in at the presentation layer. It is much more to that. It is adaptible and easy to run light weight applications, it provides a framework to integrate OR mapping, JDBC etc., Infact Struts can be used as the presentation tier in Spring.
Secondly, Struts features strictly associate with presentation stuff. It offers Tiles to bring in reuse at presentation level. It offers Modules allowing the application presentation to segregate into various modules giving more modularity there by allowing each module to have its own Custom/Default Request Processor. Spring provides Aspect Oriented programming, it also solves the seperation of concerns at a much bigger level. It allows the programmer to add the features (transactions, security, database connectivity components, logging components) etc., at the declaration level. Spring framework takes the responsibility of supplying the input parameters required for the method contracts at runtime reducing the coupling between various modules by a method called dependency injection / Inversion of Control.
Thirdly, Struts is developed with a Front Controller and dispatcher pattern. Where in all the requests go to the ActionServlet thereby routed to the module specific Request Processor which then loads the associated Form Beans, perform validations and then handovers the control to the appropriate Action class with the help of the action mapping specified in Struts-config.xml file. On the other hand, spring does not route the request in a specific way like this, rather it allows to you to design in your own way however in allowing to exploit the power of framework, it allows you to use the Aspect Oriented Programming and Inversion of Control in a great way with great deal of declarative programming with the XML. Commons framework can be integrated to leverage the validation in spring framework too. Morethan this, it provides all features like JDBC connectivity, OR Mapping etc., just to develop & run your applications on the top of this.
Another differences:
1. Struts is a web framework only, Struts can be compare with the SpringMVC. And SpringMVC is subset of the Spring framework. So we can say that Sturts can be seen as the subset of the spring framework in functionality point of view.
2. What Action class do in struts, Controller does in Spring. And action in Struts is a Abstract class but Controller in Spring is an interface, This is very good advantage of the spring.
3. Spring don�t have any action from, it bind the http form values directly into pojo. Instead of initializing the form bean spring directly initialize the domain object.
4. ActionForward in struts is replace with the ModelAndView in Spring. Model component contain the business object to be displayed via view component.
5. Unlike Struts Spring don�t provide any separate tag library.
More talk:
1.Struts implement MVC Design Patten where as Spring implements IOC Design Pattren and addreses AOP Cross cutting concerns.
2.Struts is heavy weight where as Spring is light weight framework.
3.Struts is tightly coupled Spring is loosely coupled.
Struts will be Generally used as a Front End Frame work.
Spring has spring webFlow for the same purpose, which is part of spring Framework.
The other major advatages of spring Framework is it handles
- Transaction management
- support for Messaging
- support and Integration with Other Frame works.
(Eg: Hibernate, Struts, Tapestry.. etc)
Struts Framework have some advantages
-Excellent support for Tag Library, which has wide industry acceptance.
-Easy to integare with other client side technologies.
It really a subjective matter, what for you want to use them.
both can be combindly used, to take best out of them,
or spring can alone can be used.
whenever develop applicatoion in two ways:
1.Programming through interface
2.Programming through class
Struts drawbacks:
1.better way is Programming through interfaces so that struts not support that(i.e all are predifined class.. Action,DiaspatchAction,SwitchAction)
2.This framework is tightcoupling.it is not separated layerwised
3.It is not Suuport to DependencyInjection
4.We have to hard code to use
applications like hibernate, jdbc, etc.
SPRING:
overcome the above problems Spring will be introduced
Spring Application develop through Interface
It suport DI.
It is layerwise designed.
It is loosecoupling
Spring suport MVC and Other MVC
Spring Application allways flow DesginPatterns
Spring support to POJO'S AND POJI(i.e it is not api dependent)
spring without hard coding in application as spring supports
classes hibernate, jdbc, and many more. This is very little
to say about spring. There are many features to be known.
Are You a Software Architect?
Maven Phases
Although hardly a comprehensive list, these are the most common default lifecycle phases executed.
validate: validate the project is correct and all necessary information is available
compile: compile the source code of the project
test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
package: take the compiled code and package it in its distributable format, such as a JAR.
integration-test: process and deploy the package if necessary into an environment where integration tests can be run
verify: run any checks to verify the package is valid and meets quality criteria
install: install the package into the local repository, for use as a dependency in other projects locally
deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.
There are two other Maven lifecycles of note beyond the default list above. They are
clean: cleans up artifacts created by prior builds
site: generates site documentation for this project
if we execute the compile phase, the phases that actually get executed are:
1. validate
2. generate-sources
3. process-sources
4. generate-resources
5. process-resources
6. compile
Monday, February 1, 2010
Chain of Responsibility
Chain of Responsibility is a popular technique for organizing the execution of complex processing flows. It is not difficult if you want to write it yourself but Commons Chain has already implemented this pattern for you.
Commons Chain models a computation as a series of "commands" that can be combined into a "chain". The API for a command consists of a single method (execute()
), which is passed a "context" parameter containing the dynamic state of the computation, and whose return value is a boolean that determines whether or not processing for the current chain has been completed (true), or whether processing should be delegated to the next command in the chain (false).
E.g., first I create my custom context to be passed around my flows.
import org.apache.commons.chain.impl.ContextBase;
public class MyContext extends ContextBase {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Then I created my processes, each one as a command.
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
public class Command1 implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("First command");
MyContext myContext = (MyContext)context;
myContext.setName("twit88");
return false;
}
}
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
public class Command2 implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("Second command");
MyContext myContext = (MyContext)context;
myContext.setEmail("admin@twit88.com");
return false;
}
}
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
public class Command3 implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("Third command");
MyContext myContext = (MyContext)context;
System.out.println("name: " + myContext.getName());
System.out.println("email: " + myContext.getEmail());
return false;
}
}
I defined the sequence of processing in a configuration file.
<catalog>
<!-- Single command "chains"
from CatalogBaseTestCase -->
<command name="MyFirstCommand"
className="Command1"/>
<command name="MySecondCommand"
className="Command2"/>
<command name="MySecondCommand"
className="Command3"/>
<!-- Chains with nested commands -->
<chain name="MyFlow">
<command id="1"
className="Command1"/>
<command id="2"
className="Command2"/>
<command id="3"
className="Command3"/>
</chain>
</catalog>
Then I can test it.
import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.config.ConfigParser;
import org.apache.commons.chain.impl.CatalogFactoryBase;
public class TestChain {
private static final String CONFIG_FILE = "/chain.xml";
private ConfigParser parser;
private Catalog catalog;
public TestChain() {
parser = new ConfigParser();
}
public Catalog getCatalog() throws Exception {
if (catalog == null) {
parser.parse(
this.getClass().getResource(CONFIG_FILE));
}
catalog = CatalogFactoryBase.getInstance().getCatalog();
return catalog;
}
public static void main(String[] args) throws Exception {
TestChain chain = new TestChain();
Catalog catalog = chain.getCatalog();
Command command = catalog.getCommand("MyFlow");
Context ctx = new MyContext();
command.execute(ctx);
}
}
The output
First command
Second command
Third command
name: twit88
email: admin@twit88.com
Courtsey:
http://twit88.com/blog/2008/03/17/design-pattern-design-a-simple-workflow-using-chain-of-responsibility-pattern/
Sunday, January 31, 2010
JSP Servlet Interview questions
Question1:After hitting submit button, a JSP page processes a database transaction. You have accidentally closed the browser window. Will the database transaction continue or will get over?
Answer:
The database transaction will still continue; Because a Servlet thread was created when you hit the JSP page and that runs the database transaction. Closing the browser window will not kill the Servlet thread.
Question2:What is the difference between http GET and POST methods ?
Answer:
GET method passes the form fields as part of URL, but POST method wraps or encrypts the form fields in request data; b) Also, you can pass only 255 characters to the action page with GET method.
Question:3 There are 10 servlets in your web application, and they are frequently used (sticky Servlet). How will you optimize their loading?
Answer:
Add
Question:4. How will you communicate across Servlets? (or, how will you achieve Inter Servlet communication?)
Answer:
Use RequestDispatcher.forward() and RequestDispatcher.include();
Question:5. You know the difference between RequestDispatcher.forward() and RequestDispatcher.sendRedirect(). So, which one is desirable to use?
Answer:
RequestDispatcher.sendRedirect() is desirable. Because, forward() can’t work across different JVM.
Question:6. What is the class path hierarchy for a Servlet?
Answer:
First, lookup in WEB-INF/classes, then WEB-INF/lib then from tomcat’s central library folder (
Question:7. You can’t read files (located out of tomcat directory) from JSP and Servlets for security purpose. But, how will you access those files from JSP or Servlets, in case if you need them?
Answer:
Any class from WEB-INF/classes or WEB-INF/lib can access files. So, use those classes to do the job for your JSP and Servlets.
Courtesy:http://excusemeworld.com
Java Collections API Interview Questions
Question1:You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
Answer:
LinkedList.
Question2:What goes wrong if the HashMap key has same hashCode value?
Answer:
It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
Question:3 If hashCode() method is overridden but equals() is not, for the class ‘A’, then what may go wrong if you use this class as a key in HashMap?
Answer:
Question:4. How will you remove duplicate element from a List?
Answer:
Add the List elements to Set. Duplicates will be removed.
Question:5. How will you synchronize a Collection class dynamically?
Answer:
Use the utility method
java.util.Collections.synchronizedCollection(Collection c)
Courtsey:
http://excusemeworld.com
Java Threads Interview Questions
Question 1:. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
Answer:-Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
Question 2:What happens when a thread calls notify() but no thread(s) is waiting?
Answer:-Actually…, nothing the notify() call simply returns.
Question 3:How will you declare a timer variable that will be accessed by multiple threads very frequently?
Answer:-Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
Question 4:How will you synchronize static variables?
Answer:-
Obtain class level lock.
synchronized( obj.getClass()) {……..}
Question 5:What happens when threads are waiting, but never being notified?
Java, J2EE Performance Tuning Interview Questions
Question 1:Assume a multiplication operation in java takes 10 milliseconds. So, what is the running time of the following for() loop?
int k = 10;
for(int i=0; i<100; k =" 20">
Answer:-The for loop iterates only once, not 100 times. So the running time is 10 millisecond. Because, the loop evaluates to a constant result ( that is, k = 20 * 100 will yield same result for 100 times) . So, jvm is smart enough, runs the for() loop once and saves time. I just mention this, because the developer should not worry about expression level optimization, which is taken care by the jvm itself.
Question 2: You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size).
Answer:-You can write an intelligent program in this case :). If the file size is smaller, then read the whole file content in one-go. Read an example program given here. But, what if the file size is big? In this case, the program can’t read the whole file in one shot, as it would run out of memory. So, you can write the program in such a way that it reads the file content in byte arrays for several iterations. In this case, the running time of the program will depend on the size of byte array. So, how will you smartly determine the size of byte array?You can use Runtime.getRuntime().freeMemory() to find the freely available heap size. Based on this available memory, your program can create smaller or larger byte arrays at runtime. The larger the byte arrays, the lesser the response time.
Question 3:You have to use JDBC (type 4 driver) to retrieve some values from two different tables in database. As you have to use join operation in this case, will you consider using join in the sql query level or in the program level?
Answer:-You have to move the join operation to query level. Never try to do (joining, sorting, aggregating, grouping and etc) such things application level, unless otherwise it is required. Because, SQL processor may optimize the join and prepare the better execution plan than you!
Question 4:How will you plan your optimization strategy for a given J2EE (or Java) application?
Answer:-
1. Use profiler tools (there are so many.. example is JProfiler), monitoring tools and generate reports. From the report, analyze the response time of each component.
2. First, you have to analyze the response time of read/write tasks such as: I/O, Database access. Because, that is where most of the time spent.
3. Look for poor code that doesn’t release database connection or doesn’t close files and etc.
4. Minimize the repeated interaction with components as much as possible.
Question 5: Give some strategy to optimize web tier (JSP/Servlets)?
Answer:-
1. Clearly identify static and dynamic portion of the web components. Enable client browser-level-cache for static web resource to save the network roundtrip.
2. Don’t dump all the data in session object, because that may lead your server running out of space at sometime.
3. Enable
4. Analyze whether you can zip and transfer some of the content.
Question 6: How will you tune the Data base tier?
Java Interview Questions
Question 1: Give the use and an example of the scenario where you would use serialVersionUID in a your Java class?
Question 2: Design a Employee class with name, empId, age and address fields.
Any two Employee objects are compared based on their age.
The empId is the unique id for Employee class. The Employee class can be used in Collections and HashMap.
Question 3: Explain what goes in a HashMap or Hashtable, when you store the objects with same hashcode values. Explain your answer in very depth.
Question 4: In JVM Memory, where the private, public, protected, static, String literal and object references are stored?
Question 5: How will you store your exception stack trace in a file? (you should not redirect the console output)
Question 6: What is the use of Weak, Soft, Phantom references in Garbage Collection of java? Give scenarios.
Question 7: How will you keep an object alive for ever in the JVM memory? (trick: use finalize() method)
Question8: What is the difference between JiBX and JAXB?
Answer:
JiBX can provide significant performance improvements over JAXB as it does not use reflection, but instead does byte code generation to optimize databinding.
Design Pattern Question Answer
Question 1: How will you design your Singleton Patten class to be thread-safe?
ANSWER: Adding synchronized keyword tothe getSingleton() method is inefficient solution. Initialize the static private Singleton object within Synchronized block. In this way you can achieve it.
Question 2:What Design Pattern can be used for classical Producer Consumer problem?
ANSWER: Use observer pattern (publisher subscriber model)
Question 3:M.S Word can store million lines of text. Each character in the text will have set of properties like font-color, font-size, font-style and etc. So, M.S Word application has to maintain a property structure for each and every character and that may lead to heavy storage. What design pattern will you apply to overcome this problem?
ANSWER: You have to create property group for each possible styles (font-size, font-color, font-face & etc). So, common characters will be part of a property group, there by reducing the storage of each character. This is called FlyWeight Pattern.
Question 4:Your application uses 1000 classes and they have interaction among each other. This will lead to complex communication across objects, so what design pattern can solve this problem?
ANSWER: Use Mediator pattern to separate the direct communication across objects.
Question 5:An application reads input from various clients in multiple stages and creates a binary tree structure out of all received inputs. Which design pattern can be used to design such application?
ANSWER: Building an object in multiple set - you call it Builder pattern! The realworld example is XSDBuilder class in Java.
Question 6:You have to design a budget management application for global users. But, have to provide an option to configure their native tax rules. Which design pattern, do you think, can solve this?
ANSWER: Use Template Pattern. It provides templates of methods and allowing you to override certain portion of logic.
Question 7:You have a core application class. But, you have to be able assign extra functionalities to the core class on the fly (at runtime). Which patterns deserves this purpose?
ANSWER: Decorator Pattern. This is similar to the pattern designed for java.io.* classes(BufferedReader, DataInputStream and etc.)
Question 8: How is the MVC design pattern used in Struts framework ?
Answer: In the MVC design pattern, a central Controller mediates application flow. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.
Question 9: What design patterns are used in Struts?
Answer: Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token
Question 10: Question: How would you go about analyzing performance of an application?
Answer: When performance testing a Web application, several requirements must be
determined either through interpretation of data from an existing application that
performs similar work. Those requirements are:
User base
What is the expected number of users that will access this application? This is
generally expressed in hits per month, day, hour, or minute depending on
volumes.
Total concurrent users
During a peak interval, what is the maximum possible number of users
accessing the application at the same time.
Peak request rate
How many pages will need to be served per second?