Saturday 30 April 2011

Exception chaining in java

In this tutorial we’ll discuss about exception chaining, which may be new term to few java EE developers.

Note: If at any time, you feel no need for such tutorial, execute the two programs in the post and learn what exception chaining is all about.

The most important thing to remember about Exception chaining is that we need to use the constructor of the exception classes which accepts a parameter of type Throwable so that it can keep a reference to the exception which was the cause of this exception.

Definition of Exception Chaining:

The definition of chained exceptions is that when the occurrence of one exception raises another exception then the stack trace of second exception should also include the root exception in the application logs.

Few points to remember about Chained Exceptions are:

1) Java does magic in order to support Exception Chaining but it is also the responsibility of the developer to have proper exception chaining mechanism in place in any Java based application. The application needs to be coded so as to support exception chaining.

2) If the developer doesn't take any action to have chained exception in his program, the root exceptions are lost. No exception chaining code, no chained exceptions seen.

3) Chained exceptions are different from the stack trace that we see when an exception occurs which prints the method names which we were invoked before the exception was thrown (in other words, the method stack trace)

4) Exception Chaining is internally supported by Java by storing a reference to the root exception has a member field cause which was added in JDK 1.4 and looks like:

private Throwable cause = this; (inside Throwable.java class)

5) The methods which are provided by Java in order to only support exception chaining are

Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
Throwable printStackTrace();

The basic and important point to keep in mind about chained exception is that we need to write a custom exception class which can accept an argument of type Throwable in is constructor and can invoke the super class's constructor with the parameters passed to its constructor. This will become more clear with two examples:

Without any Exception Chaining mechanism in place:


package com.vaani.exception.notchained
class MyException extends Exception { //Custom Exception class
public MyException (String msg) {
super(msg);
}
}

public class Test {

static int a[] = {1,2,3};

public static void main(String[] args) {

try {
System.out.println(a[4]); //Deliberate ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException ae) {
try {
throw new MyException("Exception Occured"); //throw custom exception
} catch (MyException me) {
me.printStackTrace();
}
}
}
}

Output:
com.vaani.exception.notchained.MyException: Exception Occured
at com.example.Test.main(Test.java:20)


With Exception Chaining mechanism in place:


package com.vaani.exception.chained;

class MyException extends Exception { //Custom Exception class
public MyException (String msg, Throwable ex) {
super(msg, ex);
}
}

public class Test {

static int a[] = {1,2,3};

public static void main(String[] args) {

try {
System.out.println(a[4]); //Deliberate ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException ae) {
try {
throw new MyException("Exception Occured",ae); //throw custom exception
} catch (MyException me) {
me.printStackTrace();
}
}
}
}

Output:

com.vaani.exception.chained.MyException: Exception Occured
at com.example.Test.main(Test.java:19)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 4
at com.example.Test.main(Test.java:16)


Please note that the use of custom exception in above examples is for demonstration only. It could be any JDK exception class like IllegalArgumentException, ClassNotFoundException or IllegalStateException.

Sorting an array using selection sort (java)

public static void main (String [] args) {
int n;
Scanner sc = new Scanner (System.in);
System.out.print ("Enter how many elements");
n = sc.nextInt();
int [] a = new int [n];

//input array
for (int i=0; i<n; i++){
System.out.print("Enter element " +(i+1) + " ");
a[i] = sc.nextInt();
}

//sorting
for (int i=0; i<n-1; i++) {
for (int j=i+1; j<n; i++) {
if(a[i]>a[j]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}

//output
for (int i=0; i<n; i++){
System.out.println(a[i]);
}

}

Finding smallest and largest number in an array (java)

public static void main(String[] args) {

int[] numbers = new int[10];
int x = 0;
int max,min ;
while (x < numbers.length) {
int random = (int) (Math.random() * 10);
numbers[x] = random;
x = x + 1;
}
x = 0;
while (x <numbers.length) {
System.out.println("Value of numbers[" +x+ "] is " +numbers[x]);
x = x + 1;
}

max = numbers[0];
min = numbers[0];
for (x=0;x<numbers.length;x++){
if(numbers[x]>max){
max=numbers[x];
}
else if(numbers[x]<min){
min=numbers[x];
}

}
System.out.println("Largest number is " +max);
System.out.println("Smallest number is " +min);


}

Factorial in java

Factorial of number using iteration

public int factorial(int var) {
if ((var) > 1) {
fact = var * factorial(var - 1);
return fact;
}

else {
return 1;
}
}


 

Factorial of number using recursion


public int factorial(int var) {
if ((var) > 1) {
fact = var * factorial(var - 1);
return fact;
}

else {
return 1;
}

Multiplying 2 matrices in java

See following code:

//Input number rows and columns in 2 matrices
Scanner sc = new Scanner (System.in);
int r1,c1;
System.out.print("Enter how many rows");
r1 = sc.nextInt();
System.out.print("Enter how many cols");
c1 = sc.nextInt();
int r2,c2;
System.out.print("Enter how many rows");
r2 = sc.nextInt();
System.out.print("Enter how many cols");
c2 = sc.nextInt();
if(c1 != r2){
System.out.println("Can't mult");
System.exit(1);
}
int m1[][] = new int[r1][c1];

//input m1
for (int i=0; i<r1; i++){
for (int j=0; j<c1; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m1[i][j] = sc.nextInt();
}
}

int m2[][] = new int[r2][c2];

//input m2
for (int i=0; i<r2; i++){
for (int j=0; j<c2; j++){
System.out.print("Enter element" + (i+1)+","+(j+1));
m2[i][j] = sc.nextInt();
}
}

int m3[][] = new int[r2][c2];

//Matrix multiplication
for (int i=0; i<r1; i++){
for (int j=0; j<c2; j++){
for (int k=0; k<c1; k++){
m3[i][j]+=m1[i][k]*m2[k][j];
}
}
}

//Output m3
for (int p=0; p<r1; p++){
for (int j=0; j<c2; j++){
System.out.print(m3[p][j]+"\t");
}
System.out.println();

}

Immutable Objects / Wrapper Class Caching

Since Java 5, wrapper class caching was introduced.
The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10; or Integer myNumber = Integer.valueOf(10);

256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:
private static class IntegerCache 
{
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static
{
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}

public static Integer valueOf(int i)
{
final int offset = 128;
if (i >= -128 && i <= 127) // must cache
{
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}


So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:

Integer i = 100;
Integer p = 100;
if (i == p)
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");
if(i.equals(p))
System.out.println("i and p contain the same value.");

The output is:
i and p are the same.
i and p contain the same value.


So this result is similar to the result as shown here for strings.

It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching. So consider the following example:

Integer i = new Integer (100);
Integer p = new Integer(100);
if(i==p)
System.out.println(“i and p are the same object”);
if(i.equals(p))
System.out.println(“ i and p contain the same value”);


In this circumstance, the output is only: i and p contain the same value

The other wrapper classes (Byte, Short, Long, Character) also contain this caching mechanism OR constant pooling mechanism. The Byte, Short and Long all contain the same caching principle to the Integer object. The Character class caches from 0 to 127. The negative cache is not created for the Character wrapper as these values do not represent a corresponding character. There is no caching for the Float object.

BigDecimal also uses caching but uses a different mechanism. While the other objects contain a inner class to deal with caching this is not true for BigDecimal, the caching is pre-defined in a static array and only covers 11 numbers, 0 to 10:

 
// Cache of common small BigDecimal values.
private static final BigDecimal zeroThroughTen[] = {
new BigDecimal(BigInteger.ZERO, 0, 0),
new BigDecimal(BigInteger.ONE, 1, 0),
new BigDecimal(BigInteger.valueOf(2), 2, 0),
new BigDecimal(BigInteger.valueOf(3), 3, 0),
new BigDecimal(BigInteger.valueOf(4), 4, 0),
new BigDecimal(BigInteger.valueOf(5), 5, 0),
new BigDecimal(BigInteger.valueOf(6), 6, 0),
new BigDecimal(BigInteger.valueOf(7), 7, 0),
new BigDecimal(BigInteger.valueOf(8), 8, 0),
new BigDecimal(BigInteger.valueOf(9), 9, 0),
new BigDecimal(BigInteger.TEN, 10, 0),
};


As per Java Language Specification(JLS) the values discussed above are stored as immutable wrapper objects. This caching has been created because it is assumed these values / objects are used more frequently.

String equality and interning in java

Strings in Java are objects, but resemble primitives (such as ints or chars) in that Java source code may contain String literals, and Strings may be concatenated using the “+” operator. These are convenient features, but the similarity of Strings to primitives sometimes causes confusion when Strings are compared.

As we saw here, how java deals with string comparisons. Lets understand the case 2, where == operator returns true for 2 different references having same values.
To save memory (and speed up testing for equality), Java supports “interning” of Strings. When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. Otherwise, the String is added to the table and a reference to it is returned. The result is that after interning, all Strings with the same content will point to the same object. This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.

Confusion can arise because Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values. Code written based on this assumption will fail in a potentially non-obvious way when the == operator is used to compare Strings with equal content but contained in different String instances.
Following test cases show how interning can be performed by java:
Consider following string i.e “A String":
 
String aString = "A String"; 



Case 1: Concatenated string


String aConcatentatedString = "A" + " " + "String";


aString == aConcatentatedString       : true
aString.equals(aConcatentatedString) : true

Case 2: Runtime string




String aRuntimeString = new String("A String");


aString == aConcatentatedString       : false
aString.equals(aConcatentatedString) : true


Case 3: Interned string


String anInternedString = aRuntimeString.intern();

aString == aConcatentatedString : true
aString.equals(aConcatentatedString) : true



Case 4: External strings , eg. 1st argument of main method


String firstArg = args[0];


aString == aConcatentatedString : false
aString.equals(aConcatentatedString) : true


Case 5: Using intern on external strings


String firstArgInterned = firstArg.intern();

aString == aConcatentatedString : true
aString.equals(aConcatentatedString) : true




So we can see that explicitly invoking intern() returns a reference to the interned String.

Similar to string, there is a pool of integers, bytes, etc and other value based classes like bigdecimal. See here for more on this.

== vs equals method in case of String and primitive types

Object equality is tested using == operator. Here it is checked whether 2 references are pointing to same object or not.
While value equality is tested using the .equals(Object) method.
So consider following code snippet:
String one = new String("abc");
String two = new String("abc");


So here

one==two is false

one.equals(two) is true

one==two, because we are creating 2 new objects as specified by new keywords. But as their values are same one.equals(two) returns true because values are same.

Now if we say:

String three = one;



Now both one==two as well one.equals(two) returns true.

Using new keyword vs not using it to create 2 strings


Now consider 2 cases, when we create 2 strings with same value, but first using new keyword and then not using new keyword:

Case1 : Using new keyword:

String data = new String("123");
String moreData = new String("123");



Here data==moreData is false.

Case 2 : Not using new keyword:

String letters = "abc";
String moreLetters = "abc";


Here data==moreData is true.

Why?

Explaining the case 1 is very simple. Because it falls inline with our earlier explanation of == and != operators. But how can we explain case 2, where string comparison using == operator, returns true.

This is due to the compiler and runtime efficiency. In the compiled class file only one set of data "abc" is stored, not two. In this situation only one object is created, therefore the equality is true between these object. Read here for more on this. Not only strings , compiler also support this type of constant pooling for integers, bytes and other value types. See here for this.


Note:

Even though one set of data "123" is stored in the class, this is still treated differently at runtime. An explicit instantiation is used to create the String objects. Therefore, in this case, two objects have been created, so the equality is false. It is important to note that "==" is always used for object equality and does not ever refer to the values in an object. Always use .equals when checking looking for a "meaningful" comparison.

Value objects or VOs in java

//to be written soon

equals() for String, StringBuilder and StringBuffer

Rule of equality in java:

Equals method should be used for checking the logical equality of objects of a class but it does not mean that every class is a candidate for overridden equals method

So if you go and see the source code of StringBuffer/StringBuilder classes in Java, you will find that equals() method is not overridden but it is overridden in the String class.

public class Test{

public static void main (String args[]) {
String str1 = "abcd";
String str2 = "abcd";
System.out.println(str1.equals(str2));

StringBuffer sb1 = new StringBuffer(str1);
StringBuffer sb2 = new StringBuffer(str1);
System.out.println(sb1.equals(sb2));
}
}

Output:

true
false


For String objects, the logical equality would mean the contents of the string should be same.

For StringBuffer and StringBuilder we have following facts:
  • Logical equality means that both objects were configured and assembled using the same String instance and not whether the contents of those String objects is same.
  • The intended use of StringBuffer and StringBuilder is for maintaining a buffer of characters which may change with time.
Both the above statements contradict with each other because the String object being used for building a StringBuffer/StringBuilder object can change very frequently and it does not make any sense to compare the StringBuffer/StringBuilder objects.

This is the reason that the equals() method is not overridden in StringBuffer/StringBuilder classes.

It should be noted that there a misconception that is going around the developer community regarding the above reason which says that then why an ArrayList/Date overrides the equals() method as it too can change with time. Here are a few reasons to clear that thought which in fact is natural:
  • StringBuffer/StringBuilder classes are intended to be used as temporary buffer and change more frequently than classes like ArrayList and Date
  • While one may like to perform various operations like serialization, making clones, being used as keys in collections or stored in database but one is very unlikely to perform similar operations with StringBuffer/StringBuilder classes.
Also String may be treated as value object, where value equality means, object equality. Read here for more on value objects.


Online java compilers

What is common between Innovation.ch, youjavait.com, ideone.comcompilr.com and browxy.com?

If you are sitting on a machine on which Java is not installed and you can not even download Java because of some reason but you have internet connectivity then there is no one stopping you from compiling and testing your source code. There are many online compilers available on the internet which can be used to see the output of the code you have written.

Some of them are powerful and some are not. Here are some of them reviewed.

1) Innovation.ch:

Positives:
a) You can specify source files using the browse button
b) You can also specify the Jar files which are required for the compilation to complete
c) You can doenload the compiled .class files individually or download a zip/gz file containing all the classes.
d) The compiler interface can be extended by creating your own HTML page and calling the JXXX compiler's cgi APIs.
e) The website can run the applets for you.
f) Supports JDK 1.5 and JDK 1.6
g) The source files can have packages.
h) There are multiple options availale to pass to the javac command.
i) Works with IE as well as Firefox.

Negatives:
a) A maximum of 5 source and 5 jar files can be specified in one go.
b) The source files should have ASCII text only.
c) You can not browse a folder to compile all the source files under the folder.

2) youjavait.com:

Positives:
a) You can specify the program to use the server JDK or local JDK (JAVA_HOME needs to be set).
b) You can maintain multiple projects.
c) You can create multiple source files with built in syntax highlighter and then you can refer these source files as they are in the same package.
d) You can use Google/OpenID account for this website and store projects for later reference.
e) Compiles and runs the program and then displays the output.

Negatives:
a) Seems to run only on IE and not Firefox
b) There is only one default package named com and you can not create more packages.
c) You can not get the compiles .class files.

3) ideone.com:

Positives:
a) Works in Firefox also.
b) It has options for multiple programming languages.
c) You can run the code to view the output.
d) You have a built in syntax highlighter.

Negatives:
a) Though the source code is available for later viewing purpose, you can not get the .class files generated by the compiler.
b) Supports only JDK 1.6

4) browxy.com:

Seems to be not working in neither Firefox and nor IE. You can try your luck with this online Java compiler and Runner.

You can see these observations, but may be some changes they must have dist, after this blog.

Programming hells you can think off

Every approach has its pros and cons but when something becomes too difficult to handle and that to frequently, it becomes a hell for us.

So a hell is nothing but a problem that comes back to you without any fault from writing the code but because of using some methodology or standard.

The problems with various approaches become more painful when the application scales.

Here are some common hells. Probably you may like to add more to the list.
1) DLL Hell:
A kind of dependency hell where Windows can't locate a DLL when you start or use an application


http://en.wikipedia.org/wiki/DLL_hell


2) XML Hell:
You keep on adding XML's and at a later stage find it very difficult to maintain (Reason why annotations in EJB3 came up)
http://java.dzone.com/news/draft-spring-xml-hell

http://aspnetresources.com/blog/welcome_to_xml_hell


3) Jar Hell:
After all the classloader have run, the required dependent class in a particular jar has not been loaded.

Or

There are so many versions of Jar files released which confuses you about the right version of jar to use.



4) Meta Data Hell:
All those who have used annotations for hard coding various kind of stuff have felt this hell.


5) Redirect Hell:
This relates to extra processing by various websites before being actually shown the page being sought. Google, Yahoo, MSFT, Facebook, Twitter- all do such things and sometimes frustrate us.


6) Dependency Hell:
Have you ever installed a game and found that the version of DirectX you have is not compatible with the game. You need to download and install the proper version.

Inner Class Nested Levels In Java

How frequently does one see inner classes being used in an application leave aside inner classes at nested levels.
Yes one can have as many nested level of inner classes . The code below proves it.

However, the usability of this code is debatable.

public class Test{
    class a1{
        class a2{
            class a3{
                class a4{
                }
            }
        }
    }
   public static void main(String[] args) {
       Test.a1.a2.a3.a4 abc = new Test().new a1().new a3().new a4().new a6();
    }
}

Passing by reference doesn't swaps in java

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
Take the badSwap() method for example:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
public void badSwap2(Point arg1,Point arg2)
{
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}

The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.



Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.

But still it is not impossible to write swap. See here for this.

Writing a swap function in java

Method 1 : Changing the data underneath
public class Swapper<T> {
     
public Swapper(T obj) {
             data_
= obj;
     
}
     
public T get() { return data_; }
     
public void set(T value) { data_ = value; }
     
public void swap(Swapper<T> o) {
           T tmp
= o.data_;
           o
.data_ = data_;
           data_
= tmp;
     
}
     
private T data_ = null;
 
}

 
// .. Now you can do:
 
Swapper<String> a = new Swapper("Hello");
 
Swapper<String> b = new Swapper("World");
 
// a.get().equals("Hello")
  a
.swap(b); // now a.get().equals("World")


But we can write function which uses the above idea:
public void Swap(RefObject<Integer> p, RefObject<Integer> q)
{
   
int temp;
   temp
= p.argvalue;
   p
.argvalue = q.argvalue;
   q
.argvalue = temp;
}
public final class RefObject<T>
{
   
public T argvalue;
   
public RefObject(T refarg)
   
{
        argvalue
= refarg;
   
}
}


Method 2 : Using Atomic reference
Example for integers:

public void swap(AtomicInteger a, AtomicInteger b){
   
  a.set(b.getAndSet(a.get()));
}
  

Above method can be written in more verbose way like this:

import java.util.concurrent.atomic.AtomicInteger;
public class TestAtomicInteger{
   
private static void swap(AtomicInteger a, AtomicInteger b) {
       
int val = a.get();
        a
.set(b.get());
        b
.set(val);
   
}

   
public static void main(String[] args) {
       
AtomicInteger a = new AtomicInteger(1);
       
AtomicInteger b = new AtomicInteger(2);

        swap
(a, b);

       
System.out.println("a: " + a + " b: " + b);
   
}
}

Example for strings:
public void swap(AtomicReference a, AtomicReference b){
        a.set(b.getAndSet(a.get()));
}


Of course this not very satisfactory, as you hardly ever develop against AtomicReferences. But basically you need to use some kind of container as shown above, because you can't just swap the references. So you can e.g. swap the elements of a two-element array or list, but you just can't swap two strings without having access to the original variables (so you can't do it in a helper function).

Case when data is in list:
If your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int).
In above function following are the function and parameters:

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged
.)
Parameters:
    list
- The list in which to swap elements.
    i
- the index of one element to be swapped.
    j
- the index of the other element to be swapped.

Case when swap is required in sorting:
apparently the real objective is to sort an array of ints. That's a one-liner with Arrays.sort(int[]):

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

To check the output:
   System.out.println(Arrays.toString(arr));
   // [1, 2, 3, 19, 25, 378]

And here is a simple helper function to swap two positions in an array of ints:

public static void swap(final int[] arr, final int pos1, final int pos2){
   final int temp = arr[pos1];
   arr[pos1] = arr[pos2];
   arr[pos2] = temp;
}

Best Way to Swap Values in Java

Though not all Java applications require variables to be swapped, but those which do require are not given proper thoughts about correct and optimized implementation.


Method-1: Using temporary Variable

The most common way to swap two values is by using a temporary variable as shown below:

int a=10,b=5,c;
c=a; (c=10,a=10,b=5)
a=b; (c=10,a=5,b=5)
b=c; (c=10,a=5,b=10)

If the use of temporary variable c is not allowed, then we have the following two options:

Method-2.1 : Using the addition and subtraction operations
int a=10,b=5;
a=a+b;
b=a-b;
a=a-b

The problem with the above solution is that the addition and subtraction can cause overflows. An overflow is a condition when the value of a variable is increased/decreased beyond the maximum/minimum value of that variable. Though the output of such a program may show that the variables have been swapped but it is not guaranteed as per Specification of various programming languages including Java.

package com.vaani.swap.subtraction;
class Test{
    public static void main (String args[]) {
            int a=1999999999,b=1899999999;
            a = a + b;
            System.out.println("After operation 1, a = " + a +
                 " b = " + b);
            b = a - b;
            System.out.println("After operation 2, a = " + a +
                 " b = " + b);
            a = a - b;
            System.out.println("After operation 3, a = " + a +
                 " b = " + b);
   }
}

Output:
After operation 1, a =  -394967298 b = 1899999999
After operation 2, a =  -394967298 b = 1999999999
After operation 3, a =  1899999999 b = 1999999999

Method-3: Using the XOR operator

The XOR operator can also be used swap two variables using the logic shown below:

int a=10,b=5;
a=a^b;
b=a^b;
a=a^b

Thank you

Java timer test

Example to show java timer:

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask {
public static void main(String[] args) { 
//define a timer 
final Timer timer = new Timer("Test Timer"); 
 
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Timer fired");
}
}, Calendar.getInstance().getTime(), 5 * 1000);

Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Canceling timer");
timer.cancel();
}
});
}
}

Friday 29 April 2011

Usage of class loaders

Java ClassLoader is a powerful tool that can be used in a various of ways to extend the possibilities of Java applications.
One of the most well-known usages of custom class loaders are Java Applets, where a class loader is used to dynamically download code from the webpage. Customized ClassLoaders are also the base element of Java Application Servers and Web Containers. ClassLoaders are one of things that make the Java platform so extensible and flexible.

Many J2EE application servers have a hot deployment capability, where we can reload an application with a new version of class definition, without bringing the server VM down. Such application servers make use of custom class loaders. Even if we don t use an application server, we can create and use custom class loaders to fine-control class loading mechanisms in our Java applications. So have fun with custom loaders. 

Getting the class loader of a class

Bootstrap class loader is pretty special, in that it is implemented in native code. All other class loaders are written in Java (apart from some native methods) and extend the java.lang.ClassLoader class. We could get the class loader which was used to load any particular class with class.getClassLoader() method:

public class ShowClassLoaders {

public static void main(String[] args) {
System.out.println("class loader for Integer: "
+ Integer.class.getClassLoader());
System.out.println("class loader for BlowfishCipher: "
+ com.sun.crypto.provider
.BlowfishCipher.class.getClassLoader());
System.out.println("class loader for this class: "
+ ShowClassLoaders.class.getClassLoader());
}
}

When we run this program, we will see the following output:
class loader for Integer: null
class loader for BlowfishCipher: sun.misc.Launcher$ExtClassLoader@9cab16
class loader for this class: sun.misc.Launcher$AppClassLoader@d9f9c3

java.lang.Integer was loaded using the bootstrap class loader. In most implementations getClassLoader() method returns null for the bootstrap class loader. com.sun.crypto.provider.BlowfishCipher class is stored inside the <JAVA_HOME>/lib/ext/sunjce_provider.jar so it was loaded with the extensions class loader. Classes implemented by us, like the class with the main method, was loaded by system class loader.