Java, how to make a thread that watches the state of a program?
I want to create a thread that will be constantly running in the background checking the state of a program as it runs. I just want to know how to keep it running and how to make开发者_JAVA百科 the thread.
Executors.newSingleThreadExecutor().submit(new ApplicationMonitor());
class ApplicationMonitor implements Runnable {
public void run() {
// do your monitoring stuff
}
}
ApplicationMonitor should never return and never allow exceptions to be thrown. Alternately, and maybe more safely, make the ApplicationMonitor do just one check, and put the submit() call in a loop. Then the monitoring can fail, and it will be restarted later:
while (true) {
try {
Future<?> future = Executors.newSingleThreadExecutor().submit(
new ApplicationMonitor());
future.get(); // can add a timeout here to limit the monitoring thread
} catch (Exception e) {
reportMonitoringException(e);
}
sleepUntilNextMonitoringCycle();
}
Finally, you can have Java do the scheduling for you:
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(
new ApplicationMonitor(), 0, 30, TimeUnit.MINUTES);
With this approach, you can't get a Future for all the scheduled invocations, so your exceptions would have to be handled within the ApplicationMonitor.
You know there is a Thread
class, right?
Thread t = new Thread(new Runnable(){
@Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}
});
t.start();
For future reference, I'd recommend reading Java Concurrency in Practice if you're going to continue developing multi-threaded applications.
EDIT - Also, if you require more sophistication, I recommend reading up on the Executors
framework.
Implement a Runnable that checks the state of your program (how the state of your program is checked is of course up to you to figure out), then give it to a Thread and start the thread.
There are a couple of examples in the javadocs I've linked that provide a basis for your code. For more details and more advanced concurrency facilities, check out the Java Concurrency learning trail.
You'll need to do two main things:
- Start your monitoring thread (see @Moonbeam's answer)
- Make the target program suitable for monitoring
To achieve the second item is a lot more complex than you might think. Things to consider are:
- making any fields you are watching
volatile
- using synchronized access to groups of fields that together comprise a consistent state, so that updates are "atomic"
精彩评论