无限for循环的问题
我是java编程的stater...我正在编写一个调度程序。我正在从属性文件中读取日期和时间值。如果属性文件中有任何更改,那么我必须重新安排调度程序。因此,为此,我正在编写一个无限 for 循环,如下所示:
for(;;){
result = loadData.checkChanges();
if(result == true){
//If changes found in the properties file then reSchedule tasks
reSchedule();
}
}
如果循环运行到“应用程序服务器”中应用程序的生命周期(一年或两年),会遇到性能问题或者JVM问题或者还有其他问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非您的
checkChanges()
方法休眠或阻塞,否则当前编写的代码将通过以处理器能够承受的速度调用loadData.checkChanges();
来对 CPU 造成严重影响。理想情况下,您应该执行诸如调用 loadData.wait() 之类的操作,然后在您希望运行检查时让另一个线程调用 loadData.notify() 。一个更简单且几乎同样好的解决方案是定期使线程休眠,例如:此外,请不要使用
for(;;)
。相反,尝试使用while(true)
,这样就清楚多了。或者更好的是,尝试while(!stop)
,其中stop
是一个布尔变量,当应用程序上下文被破坏(服务器关闭、Web 应用程序取消部署等)时,该变量会设置为 true。 )。Unless your
checkChanges()
method sleeps or blocks, the code as currently written will thrash the CPU by callingloadData.checkChanges();
as fast as the processor is able. Ideally you should do something like callloadData.wait()
, and then have another thread callloadData.notify()
when you would like the check to run. A simpler and nearly as good solution is to sleep the thread periodically, like:Also, please don't use
for(;;)
. Instead trywhile(true)
, it's so much clearer. Or even better, trywhile(!stop)
wherestop
is a boolean variable that gets set to true when your application context is destroyed (server shutdown, webapp undeploy, etc.).这将是巨大的 cpu 占用者,因为它正在运行一个无限循环,没有任何轮询或等待机制。最好使用 java Executor API 来完成此类工作: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html
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
如前所述,CPU 将达到极限。
但是您可以通过在循环结束时等待一段固定的时间(例如 1 秒)来轻松防止这种情况:
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: