0

I use FileAlterationMonitor from Apache and I would like to know when it is done initializing. I call

fileAlterationMonitor.start();

which starts a new thread and my program moves on, before fileAlterationMonitor is done initializing. I would like to wait for the initialization to complete, but I cannot find a way to check when it is done.

I can sleep for a while, but how long to wait will vary based on speed of the computer.

I have looked at CountDownLatch and that seems simple enough in my own code, but how do I use it on FileAlterationMonitor? It cannot be extend it as it is final.

Is there a better solution than waiting "long enough"?

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
korsgaard
  • 84
  • 8

1 Answers1

0

you can use CountDownLatch and add FileAlterationObserver which would count the latch on #initialize() to the tail of observers.

this might be implemented like following:

    {

        FileAlterationMonitor monitor = new FileAlterationMonitor();
        Iterator<FileAlterationObserver> iterator = monitor.getObservers().iterator();

        FileAlterationObserver last = null;
        while (iterator.hasNext()) {
            last = iterator.next();
        }

        final CountDownLatch cdl = new CountDownLatch(1);

        monitor.removeObserver(last);
        monitor.addObserver(new FileAlterationObserver(last.getDirectory(), last.getFileFilter()) {

            @Override
            public void initialize() throws Exception {
                super.initialize();
                cdl.countDown();
            }
        });

        try {
            // wait until last observer would be initialized
            monitor.start();
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
hahn
  • 3,588
  • 20
  • 31