Saturday, March 15, 2008

Servlet Instantiation

Step 1.
Container reads the Deployment descriptor and read the servlets class name element value
say for example:


<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.mycompany.MyServlet</servlet-class> <!-- This value will be read.
<init-param>
<param-name>myVariable</param-name>
<param-value>1</param-value>
</init-param>
</servlet>

Step 2:
The container loads the class
Class clazz = Class.forName("com.mycompany.MyServlet");

Step 3:
Creates an Instance of the Servelt class,
Servlet objServlet = clazz.newInstance();

The above step will invoke the default contstructor (Zero parameter constructor of the servelt class. The spec dictates that Servlet Code should have a constructor with zero paremeter i.e default constructor).

Step 4:
The container then reads the initialization parameter "init-param" xml tags, and constructs a ServletConfig object and inovkes the
objServlet.init(config)


In simple words the ServletContainer instantiates your servlet. Since ServletContainer does not know what are the parameters to be passed, it calls default constructor i.e. with no arguments

A servlet is still just a class, so of course you can instantiate it. You can even have constructors taking arguments.

like..MyServlet = new myServlet();


But for the container to be able to use your servlet, it needs a public no-argument constructor. It would also not really make sense to instantiate the servlet yourself, because the container is responsible for the life cycle.

Saturday, March 8, 2008

The Exception Controversy

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack .
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
The Three Kinds of Exceptions
The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from.
User supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
Checked exceptions are subject to the Catch or Specify Requirement
The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.
Errors and runtime exceptions are collectively known as unchecked exceptions.

Advantage 1: Separating Error-Handling Code from "Regular" Code
Advantage 2: Propagating Errors Up the Call Stack
Advantage 3: Grouping and Differentiating Error Types

Now..The Exception Controversy

Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Howzzaaaaat!!!

Strings Strings Strings

Strings are IMMUTABLE


Strings are value objects. Value objects should always be immutable. If youwant a different value (different String), you need a different object.
String is Immutable String is the most used immutable class in Java. If new Java developers had to deal with a mutable String they may get very frustrated and overwhelmed by the complexity of the object model and give up on Java not long after starting.
String s = "nothing special";
s.toUppercase();

This does not modify the variable s at all. Instead, a new String object is created with all the characters of s changed to upper case. Since the new object is not assigned to anything, it is simply loses all references (as the toUpperCase method has completed) and is eventually garbage collected.

On the other hand, you could write it like this:


String s = "nothing special";
s = s.toUppercase();

In this example, s is now in all upper case letters, but it is not the same object as the one that was instantiated in the first line. The new String object that is returned from toUpperCase becomes assigned to s, and the original object loses its last reference and gets garbage collected.

SAFETY
If step A of a process receives a String and checks it, youdon't want some programmer to modify it before it reaches step B where it's assumed to have been OKed by A.


If they were mutable, imagine doing


getClass().getName().someModifyingOperation();


Good luck finding that class again, Mr. Classloader



Let me first tell you what is StringBuilder. StringBuilder is a class analogous to StringBuffer added in JDK 1.5. This class is designed to use in place where StringBuffer is used by single thread(like in most of the cases). According to documentation, StringBuilder should work faster than StringBuffer. So " thread unsafe, fast".I was reading one of the posts of orkut Java community asking "what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer". Valid question !


GC need to work little more in case of String, but thats fair. As a java wellwisher let me try to do some publicity of Java API :D. And here it goes:No don't use String class for concatenation operation, always use StringBuffer/StringBuilder and let me tell you why ?


This is a simple Java code for string addition in String and StringBuffer:
class StringTest {
public static void main(String[] args)
{
String s = "just a string";
s = s + "add me too";
System.out.println(s);
/*
StringBuffer s = new StringBuffer("just a string") ;
//StringBuilder s = new StringBuilder("just a string");
s = s.append("add me too");System.out.println(s);
*/
}
}
now have a look on the bytecode of this program
>> javac StringTest.java
>> javap -c StringTest
Just see line no. 11. Interesting, the plus sign we used for addition is not as innocent as it looks. String itself use StringBuffer(StringBuilder) to add two strings and hence taking much more time than normal append operation done by StringBuffer.
Let me give you more evidence, run verbose option and check the time
>> javac -verbose StringTest.java
and check the other one, that is, with StringBuffer one.You can clearly figure out the time difference and make a try with StringBuilder, time should reduce furthermore.

Friday, March 7, 2008

Overidding Static???

How to override static methods ?

I know, I know. You can't override static methods. The title was just a trick to provoke your interest :-) In this post, I'll first try to explain why it is impossible to override static methods and then provide two common ways to do it.
Or rather - two ways to achieve the same effect.
So, what's the problem?

There are situations where you wish you could substitute or extend functionality of existing static members - for example, provide different implementations for it and be able to switch implementations at runtime.

For example, let's consider a static class Log with two static methods:public static class Log
{
public static void Message(string message){ ... }
public static void Error(Exception exception){ ... }
}
Let's say your code calls Log.Message and Log.Error all over the place and you would like to have different logging behaviors - logging to console and to the Debug/Trace listeners. Moreover, you would like to switch logging at runtime based on selected options.


Why can't we override static members?
Really, why? If you think about it, this is just common sense. Overriding usual (instance) members uses the virtual dispatch mechanism to separate the contract from the implementation. The contract is known at compile time (instance member signature), but the implementation is only known at runtime (concrete type of object provides a concrete implementation). You don't know the concrete type of the implementation at compile time.

This is an important thing to understand: when types inherit from other types, they fulfil a common contract, whereas static types are not bound by any contract (from the pure OOP point of view). There's no technical way in the language to tie two static types together with an "inheritance" contract. If you would "override" the Log method in two different places, how do we know which one we are calling here: Log.Message("what is the implementation?")
With static members, you call them by explicitly specifying the type on which they are defined. Which means, you directly call the implementation, which, again, is not bound to any contract.
By the way, that's why static members can't implement interfaces. And that's why virtual dispatch is useless here - all clients directly call the implementation, without any contract.
Let's get back to our problem

Solution 1: Strategy + Singleton

Yes, that's easy. Define a contract to use and it will be automatically separated from the implementation. (Unless you make it sealed. By making a type or a member sealed, you guarantee that no one else can implement this contract.)

OK, so here's our contract:

public abstract class Logger
{
public abstract void Message(string message);
public abstract void Error(Exception exception);
}


You could make it an interface as well, but with an interface you wouldn't be able to change the contract later without breaking existing clients.

You'll only need one instance of a logging behavior, so let's create a singleton:public static class

Log
{
public static Logger Instance { get; set; } ...
}


Correct Singleton implementation is not part of this discussion - there is a whole science of how to correctly implement Singleton in .NET - just use your favorite search engine if you're curious.
Now we just redirect the static methods to instance methods of the Logger instance and presto:

public static void Message(string message)
{
Instance.Message(message);
}


And that's it! All of your code continues to use Log.Message and Log.Error, and if you'd like to change the behavior, just say Log.Instance = new DebugWriteLineLogger();

Thursday, March 6, 2008

Hashmap Cloning

Clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

“clone”creates and returns a copy of the object. It makes another object of the class in memory. Suppose, We are creating a clone of the object x then x.clone() != x will return true but it is not necessary that x.clone().equals(x) will return true. It depends upon the implementation of class.Class should implement “Cloneable” interface in order to make clone of its objects. Otherwise “CloneNotSupportedException” will be thrown.

Array,HashMap are considered to have implemented the interface “Cloneable”. If by assignment, the contents of the fields of class are not themselves cloned then this method performs shallow copy of this object, not a deep copy operation.

Let's pretend that we can peer deep inside the JVM and actually see thememory locations themselves that are the references. I'll put the memory locations of each object in parentheses.

If we have a hashmap, it might contain 3 K/V pairs:
hashmap1(1000)

keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

If you assign hashmap2 = hashmap1, then you have two references to the samehashmap object. That means that if you were to peer inside hashmap2, youare looking at the exact same hashmap object. Note that using this example,both references point to location 1000:

hashmap2 = hashmap1
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

hashmap2(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

If you do a shallow clone of hashmap1 instead, you will have two hashmapobjects, but with all the same keys and values:
hashmap2 = (Hashmap)hashmap1.clone();
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

hashmap2(3000) <-----note-----
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

If you were able to do a deep(er) clone (using your own technique) you mightend up two objects, with copies of all the keys and values:

hashmap2 = magicDeepCloneMethod(hashmap1);
-----------------------------------------
hashmap1(1000)
keyA(2000)---valueA(2010)
keyB(2020)---valueB(2030)
keyC(2040)---valueC(2050)

hashmap2(3000)
keyA(4000)---valueA(4010)
keyB(4020)---valueB(4030)
keyC(4040)---valueC(4050)