How to implement a program that will run in background

Hi, I am implementing a jabber bot that’'s supposed to do something when it receives mesages. My question is how I can make the program keep running. I guess the idea of threading would help but I just dunno how to do it. some hints will be appreciated. I dun wanna put a while(true){} there it just takes too much CPU time.

If you really don’‘t want learn threading, then the following might help. It should work (I haven’‘t tested it), but whether it’'s stable enough is up to you

Just so you know what’‘s going on, this is like a while(true) that doesn’‘t hog the CPU because it tells the operating system: "I’‘m waiting for ever, wake me up by doomsday." In other words, your program will go to the background (because the main thread finishes) but the JVM won’‘t kill it because there’'s still a non-daemon thread alive.

Thread bgThread;

main() {

// Here you setup Smack and add your packet listeners.

bgThread = new Thread(new Runnable() {

public synchronized void run() {

try {

while (!Thread.interrupted()) {

wait();

}

} catch (InterruptedException e) {

// Goodbye cruel world!

}

}

}, “Aengel”);

bgThread.start();

}

Then, when (and if) you want to close your application:

bgThread.interrupt(); // This will do the trick.

If you don’'t interrupt your background task your program will run forever in the background (or until you kill it from the operating system).

Anyway, I suggest you check the Javadocs of the Object.wait method, because you can use this background thread as a general idle thread to do background chores (like calculating Pi, finding the ultimate answer or even something useful).

By the way, to remain on topic… Smack threads are born to be daemon threads (paradoxically not because they’‘re evil), that’‘s why your application is being shut down once you return from the main method. The JVM doesn’‘t like it when it’‘s surrounded by daemon threads and likes to always keep the company of at least one non-daemon thread (an Aengel thread). In other words, if left in bad company the JVM will commit suicide (note to young readers: what really happens is that the JVM goes to heaven to later reincarnate as a new JVM with a brand new zeroed out heap! Or, if it’‘s been a bad boy, in a .NET VM. But that doesn’'t happen too often).