Java 7 WatchService: avoiding an infinite loop of events when changing the event source in the handler

Basically, I am using the new Java 7 WatchService to monitor the directory.

I have a chain of handlers that listen for every I / O event thrown by a directory.

The problem is that some of the handlers must somehow change the cause of these IO events (== files). For example, if someone puts a file in a controlled folder, one of the handlers can change its extension, add something to it a file name or something else.

These actions, of course, trigger new I / O events, and the above handlers receive them. Then they make their changes again. This obviously leads to an endless loop ...

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

Basically, I would like to start event handlers only when the event was not triggered by the action of these handlers.

UPDATE: As for the solution, I would rather make a change only in the main code of the event router than worry about it in every handler that I write ("the handler makes changes only if didn" do it earlier ").

+4
source share
2 answers

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

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

Even though your handler will still receive the event for the new <file>.foo , you can drop it by stopping the "endless" distribution of events.

+4
source

I suggest using a new thread every time your event handling code raises a new event. Inside the event descriptor, check if the modified file needs to be renamed, if so, start a new thread that renames if you do not return from the event. In doing so, avoid endless loops, as the event handling code exits in some way.

0
source

Source: https://habr.com/ru/post/1384485/


All Articles