Java 7 WatchService:在更改处理程序中的事件源时避免事件无限循环

发布于 2024-12-19 11:54:09 字数 439 浏览 0 评论 0原文

基本上,我使用全新的 Java 7 WatchService 来监视目录。

我有一个处理程序链来监听目录发出的每个 IO 事件。

问题是某些处理程序需要以某种方式更改这些 IO 事件(== 文件)的原因。例如,如果有人将文件放入受监视的文件夹中,则处理程序之一可能会更改其扩展名,在其文件名中附加某些内容,等等。

这些操作当然会触发新的 IO 事件,并且上述处理程序会获取它们。然后他们再次进行更改。这显然会导致无限循环...

Java是否提供任何方法来处理这种情况?如果没有,你会如何处理这个问题?

基本上,我想仅当事件不是由这些处理程序的操作引起时才运行我的事件处理程序。

更新:至于解决方案,我宁愿只在主事件路由器的代码中进行更改,也不愿在我编写的每个处理程序中担心这一点(“处理程序仅在不执行更改时才进行更改”)之前”)。

Basically, I'm using the fresh new Java's 7 WatchService to monitor a directory.

I have a chain of handlers listening to every IO event issued by the directory.

The problem is some of the handlers need to change the reason of those IO events (== files) in some way. For example, if somebody puts a file into the monitored folder, one of the handlers might change it's extension, append something to it's file name, or whatever.

Those actions of course trigger new IO events and the aforementioned handlers get them. Then they once again do their changes. This obviously leads to an infinite loop...

Does Java offer any way to handle this kind of situation? If not, how would you deal with this?

Basically I'd like to run my event handlers only when the event wasn't caused by those handlers' action.

UPDATE: As for the solution, I'd rather make a change only the in the main event router's code than worry about this in every handler I write ("handler makes a change only if didn't do it before").

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光的暖冬 2024-12-26 11:54:09

如果没有基本情况,这只会导致无限循环。

假设人们将文件放入扩展名为“.bar”的目录中,而您想要扩展名为“.foo”,那么,当且仅当当前扩展名是“.bar”时,您的处理程序才会进行更改。

即使您的处理程序仍会获取新 .foo 的事件,您也可以丢弃它,从而停止“无限”事件传播。

This only leads to an infinite loop if there's no base case.

Suppose people put files in the directory with extension '.bar', and you want extension '.foo', well, your handler makes that change if and only if the current extension is '.bar'.

Even though your handler will still get an event for the new <file>.foo, you can discard it, stopping the "infinite" event propagation.

一笔一画续写前缘 2024-12-26 11:54:09

我建议每次处理事件的代码触发新事件时都使用新线程。在事件句柄中检查更改的文件是否需要重命名,如果需要,则启动一个新线程进行重命名,如果不需要从事件返回。
这样做可以避免无限循环,因为事件处理代码会以任何方式退出。

I suggest to use a new Thread every time your code handling an event would trigger a new event. Inside your event handle check if the changed file needs a rename, if yes start a new thread doing the rename, if not return from the event.
Doing it that way avoid infinite loops, since the event handling code exits in any way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文