Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileObserver instance is being garbage collected

I need to monitor all files in a folder, when a file opened (FileObserver.OPEN) I want to execute a method. The problem is some times, the FileObserver instance is collected by GC, I tried this:

    final MyFileObserver fo = new MyFileObserver("/mnt/sdcard/Musicas");
    threadFileObserver = new Runnable() {
        @Override
        public void run() {
            fo.startWatching();
        }
    };
    t = new Thread(threadFileObserver);
    t.run();

But is being collected. The question is, what is the best solution for a instance of FileObserver not be collected?

tks!!!

like image 500
danilodeveloper Avatar asked Sep 13 '25 10:09

danilodeveloper


1 Answers

I'm guessing the startWatching() method returns immediately, your Thread finishes running, and your method returns. At this point, your FileObserver, being a local variable, is not visible from anywhere. Your thread has finished running and there is no reference to it. Both are garbage collected. Define the FileObserver as a static variable or a field in something that isn't garbage collected, not as a local variable in a method.

like image 96
juell Avatar answered Sep 14 '25 23:09

juell