I have the following code:
public static void main(String[] args) {
// login event
String event = "login";
System.out.printf("Handling event: %s %s\n",event,getCurrentLogin());
sendMessage(event, getCurrentLogin());
// logout or shutdown event
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
String event = "logout";
System.out.printf("Handling event: %s %s\n",event,getCurrentLogin());
sendMessage(event, getCurrentLogin());
}
}));
}
It's a very simple program for logging user's login and logout. The problem is that the program exits when reaches the end of function main().
Am I using to the shutdown event hook correctly? I don't want to create a complex windows service, it must be a very simple application cause it will be used for remote connected windows sessions.
Do you have any suggesion for background waiting for the login termination ?
The ShutdownHook is a thread that is executed when the JVM is exiting and the program is not doing anything after you execute the "sendMessage":
You should wait for a signal to exit, like a Ctrl+C on the console. Just wait for a lock or Semaphore to avoid the program finalization, and that lock should be released when you need to finish it.