Wednesday 8 July 2009

Writing a JVM shutdown hook

Following is the class which exits on some condition. So before exit, if we need to carry out some task, register a shutdown hook(TestShutdownHook.java) with JVM


public class Test {

public static void main(String args[]){

Test test = new Test();
TestShutdownHook testshutdownHook = new TestShutdownHook(test);
Runtime.getRuntime().addShutdownHook(testshutdownHook);
test.startTest();

}

private void startTest() {

int counter = 0;
while(true){
if(counter == 100){
System.exit(0);
}
System.out.println("Running..");
counter++;
}
}

public void beforeShutdownDothis() {
System.out.println("Doing somethig before shutdown");
}
}

package com.my;

public class TestShutdownHook extends Thread {

private Test test;

public TestShutdownHook(Test test){
this.test = test;
}

public void run(){
test.beforeShutdownDothis();
}
}

Useful tips for Spring beans initialization

Referring to Constants in the bean initilization







Using the static factory for creating NON singleton beans. Even though, parameters are in 'constructor-arg' element, those are treated as normal parameters to method call.



0


test


0



Write the following code in the class which implements BeanFactoryAware , InitializingBean interfaces.

String testFileSystemNames[] = {"/","/usr","/exports"};
Object args[] = new Object[3];
List fileSystemObjects = new ArrayList();
for(int i=0; i< testFileSystemNames.length; i++ ){
args[0]=i+1;
args[1]=testFileSystemNames[i];
args[2]=i;
FileSystem fileSystem = (FileSystem)beanFactory.getBean("fileSystem", args);
fileSystemObjects.add(fileSystem);
}