Reputation: 21
I am stater in java programming ... I am writing a scheduler. I am reading date and time values from a properties file. If there are any changes in the properties file then i have to reschedule the scheduler.. so for this i am writing an infinite for loop as shown:
for(;;){
result = loadData.checkChanges();
if(result == true){
//If changes found in the properties file then reSchedule tasks
reSchedule();
}
}
If the loop runs until the life of the application in "application server"(one year or two years), will it encounter any performance problems or JVM problems or are there any other problems?
Upvotes: 2
Views: 280
Reputation: 93010
As already stated, the CPU will max out. But you can easily prevent that by waiting for some fixed amount of time, e.g. 1 sec, at the end of the loop:
try { Thread.sleep(1000); } catch (InterruptedException ex) {}
Upvotes: 1
Reputation: 54796
Unless your checkChanges()
method sleeps or blocks, the code as currently written will thrash the CPU by calling loadData.checkChanges();
as fast as the processor is able. Ideally you should do something like call loadData.wait()
, and then have another thread call loadData.notify()
when you would like the check to run. A simpler and nearly as good solution is to sleep the thread periodically, like:
for(;;){
result = loadData.checkChanges();
if(result == true){
//If changes found in the properties file then reSchedule tasks
reSchedule();
}
try {
Thread.sleep(100);
}
catch (InterruptedException ignored) {}
}
Also, please don't use for(;;)
. Instead try while(true)
, it's so much clearer. Or even better, try while(!stop)
where stop
is a boolean variable that gets set to true when your application context is destroyed (server shutdown, webapp undeploy, etc.).
Upvotes: 3
Reputation: 784898
This is going to be huge cpu hogger as this is running an infinite loop without any polling or wait mechanism. Better to use java Executor API for this kind of job: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html
Upvotes: 1