Wednesday, November 18, 2009

Handling "Ctrl+C" in Java

It is very simple. One just need to use addShutdownHook method and pass a thread where you can add code to do what ever you wanted to.
Sample code is here -

public class ShutdownHookDemo {

public static void main(String[] args)
{
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run()
{
System.out.println("Ctrl+C was pressed by some one and I am exiting now");
}
});

int i = 0;
while(true)
{
System.out.println("I value:" + i++);
System.out.println("Going to sleep now for 2 secs");
try{
Thread.currentThread().sleep(2000);
}
catch(InterruptedException ie)
{
System.out.println("Someone woke me up:("+ ie);
ie.printStackTrace();
}
}
}
}

So simple it is.. isn't it? and I just realized that hadoop used it to close files opened when some one press "ctrl+C". Just one sentence to describe it "Simple yet powerful."

No comments: