Reputation: 71
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").
Upvotes: 4
Views: 1489
Reputation: 875
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.
Upvotes: 0
Reputation: 77044
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.
Upvotes: 4