Dane Balia Dane Balia - 2 months ago 15
Java Question

Observer pattern Right for File Monitoring?

I am interested to know if the Observer Pattern is correct approach for implementing code to monitor log files and their changes?

I am currently using it, but there seems to be an anomaly that I can't quite explain. Basically, i create a Class called FileMonitor that has a timer that fires, that iterates a list of unique files looking for a changed "lastmodified date".

Upon finding it, a list of Listeners are iterated through to find the matching file, and it's
fileChanged event is notified. It then begins to process the lines that were added in the file.

So to make my question more succinct:

  1. Does the Observer Pattern fit what I am trying to do? (Currently
    I have one Listener per file)

  2. Is there any possibility of 'concurrency issues' given that there is more than one File to



If you do not want to use Java 7, you can get the same behavior with Apache IO.

From the official documentation:

FileAlterationObserver represents the state of files below a root directory, checking the filesystem and notifying listeners of create, change or delete events.

Here is how you can add listeners to define operations to be executed when such events happen.

  File directory = new File(new File("."), "src");
  FileAlterationObserver observer = new FileAlterationObserver(directory);

You will have to register the oberver(s) with a FileAlterationMonitor. Continuing from the same documentation:

  long interval = ...
  FileAlterationMonitor monitor = new FileAlterationMonitor(interval);

Where interval is the amount of time (in miliseconds) to wait between checks of the file system.

Look for package named org.apache.commons.io.monitor in the library.