Java while 循环和线程! [英] Java while loop and Threads!

查看:18
本文介绍了Java while 循环和线程!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以不断轮询数据库以了解某些字段的值的变化.它在后台运行,目前使用 while(true) 和 sleep() 方法来设置间隔.我想知道这是否是一个好习惯?而且,什么是更有效的实现方式?该程序旨在始终运行.

I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.

因此,停止程序的唯一方法是对进程 ID 发出终止命令.该程序可能处于 JDBC 调用的中间.我怎样才能更优雅地终止它?我知道最好的选择是通过使用由线程定期检查的标志来设计某种退出策略.但是,我想不出改变这个标志值的方法/条件.有什么想法吗?

Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas?

推荐答案

我想知道这是否是一个好习惯?

I am wondering if this is a good practice?

没有.这样不好.有时,这就是你所拥有的,但并不好.

No. It's not good. Sometimes, it's all you've got, but it's not good.

还有什么是更有效的实现方式?

And, what could be a more efficient way to implement this?

事物最初是如何进入数据库的?

How do things get into the database in the first place?

最好的更改是修复插入/更新数据库的程序,以向数据库和您的程序发出请求.JMS 主题非常适合这种事情.

The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.

下一个最好的更改是向数据库添加触发器以将每个插入/更新事件排入队列.该队列可以提供一个 JMS 主题(或队列)供您的程序处理.

The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.

后备计划是您的轮询循环.

The fall-back plan is your polling loop.

然而,您的轮询循环不应该是微不足道的.它应该将一条消息放入队列中,以供其他 JDBC 进程处理.终止请求是另一个可以放入 JMS 队列的消息.当您的程序收到终止消息时,它绝对必须完成先前的 JDBC 请求并且可以正常停止.

Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.

在做任何这些之前,先看看 ESB 解决方案.Sun 的 JCAPSTIBCO 已经有了这个.开源 ESB,如 MulesourceJitterbit 可能已经构建并测试了此功能.

Before doing any of this, look at ESB solutions. Sun's JCAPS or TIBCO already have this. An open source ESB like Mulesource or Jitterbit may already have this functionality already built and tested.

这篇关于Java while 循环和线程!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆