0

I am new to the java multithreading programming. I know that it can be done by thread communication but i don't know how to proceed. I don't know how one thread would notify another if some changes are done in a file. The problem is mentioned below.

I have a comma separated file in which some lines are written. I want two threads to be started from my main thread. The csv file might be appended externally/manually. One of the thread will notify second thread if some changes are done in csv file and second thread will read that file concurrently line by line and perform some task.

Thanks.

eucalypto
  • 1
  • 5
  • Maybe the Observer pattern might help out. – Stultuske Aug 25 '15 at 08:00
  • You can simply [watch for file changes](http://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory); no communication needed. – Amadan Aug 25 '15 at 08:05

2 Answers2

3

You can use java.nio.file.WatchService for this purpose.
Refer Tutorial

From the link:-

The Watch Service API is designed for applications that need to be notified about file change events. It is well suited for any application, like an editor or IDE, that potentially has many open files and needs to ensure that the files are synchronized with the file system. It is also well suited for an application server that watches a directory, perhaps waiting for .jsp or .jar files to drop, in order to deploy them.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
  • I thought the question is more on the multi-threading, not on how to monitor a change on specific file(s).. any way. This answer helps me :) thanks. – Ferdinand Neman Aug 25 '15 at 08:24
  • Why you want to reinvent the wheel, when it's already there ? :-) Java has a beautiful api for the task @EucaLypto wants to perform, why not use it. – Amit Bhati Aug 25 '15 at 08:31
  • For learning purpose ? To know how it works underneath ? Its not to reinvent, but to learn. This guy expresses that he is new in Multi-threading, and he want to explore the case of file watcher done in two thread. And I am answering exactly that. – Ferdinand Neman Aug 25 '15 at 08:34
0

You create two thread, that inside their run method, they both use one Object as the thread wait and notify signal.

The first thread (T1), would synchronize on the object and wait on it. The second thread (T2), would synchronize on the object, do something with it, and signal a notify.

The following snippets should give you idea... (please disregard about the endless loop and bad exception handling, its just to express the idea for ease of understanding).

public class IdeaOfThreadingWithWaitAndNotify {

    public static void main(String[] args)  {
        File f = new File("grow.txt");
        if(!f.exists()) {
            try {
                f.createNewFile();
                Thread appenderThread = new Thread(new FileAppender(f));
                Thread checkerThread = new Thread(new FileSizeCounter(f));
                appenderThread.start();
                checkerThread.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static class FileAppender implements Runnable {
        private File file;
        private FileOutputStream fos;
        public FileAppender(File file) throws FileNotFoundException {
            super();
            this.file = file;
            fos = new FileOutputStream(file);
        }
        public void run() {
            while(true) {
                synchronized (file) {                   
                    try {
                        fos.write("Appended... ".getBytes());
                        fos.flush();
                        file.notify();
                        Thread.sleep(1000);
                    } catch (IOException e) {
                    } catch (InterruptedException e) {
                    }
                }
            }
        }

    }

    public static class FileSizeCounter implements Runnable {
        private File file;
        public FileSizeCounter(File file) {
            super();
            this.file = file;
        }
        public void run() {
            while(true) {
                synchronized (file) {
                    try {
                        file.wait();
                    } catch (InterruptedException e) {
                    }
                    System.out.println("File changed .. now size is " + file.length());
                    // you can do other stuff with the file...
                }
            }
        }
    }
}

there you can see, between the two thread, they are sharing the same "file" instance and use it as the wait and notify signaling. Object who call the wait will have its execution flow stop right there, until the other thread call a notify on it. Then the waiting thread can continue.

I hope this helps.

Ferdinand Neman
  • 680
  • 3
  • 6