Soham Banerjee
Soham Banerjee

Reputation: 465

How to prevent a thread from being terminated when conditions are not satisfied momentarily?

This code simply processes some files whenever they are present in a preset folder. But while running on Eclipse, the thread is terminated when there are no files in the folder, although files are generally added later on. To keep it running always, I have added an infinite while loop in the run function. This works, but is there any other way to achieve this so that it uses lesser memory? Here's the code:-

import java.io.*;

public class AddService extends Thread{

public void run(){
    while(true){
    Handler obj=new Handler();
    File[] listOfFiles=obj.getFileList();
    if(listOfFiles.length>0)
    {           
        obj.process(listOfFiles);
    }
    else{
        try{

            AddService.sleep(1000);
        }
        catch(Exception ex){
        }
        }
    }
    }

public static void main(String args[]){
    AddService t1=new AddService();     
        t1.start();     
}
}

Upvotes: 2

Views: 335

Answers (3)

Victor
Victor

Reputation: 2546

A nice approach is to use a BlockingQueue (from the Java API). One thread tries to take a File from the queue, waiting until one is provided. One thread (or threads) are executed in a scheduled fashion trying to discover new files:

fileQueue = new LinkedBlockingQueue<>();
threadPool =  Executors.newFixedThreadPool(1);
threadPool.submit(new Runnable() {

   @Override
   public void run() {

        while (true)
        {
            //Block and wait for a file
            File file = fileQueue.take();
            // Do your stuff here
         }
   }
}

You can wrap this code in a loop, waiting for files and, as soon as they appear, put them in the Queue so the blocked thread can process them for you.

Upvotes: 1

jbx
jbx

Reputation: 22128

Apart from the approaches suggested by the other answers, you could also use the NIO WatchService provided by the JDK itself.

You can follow the tutorial here, which shows you how to monitor a directory for changes (new files added, existent files modified, or files deleted).

http://docs.oracle.com/javase/tutorial/essential/io/notification.html

So you could check if there are any files in the directory and if not, create a watcher that notifies you when there is a change.

Upvotes: 1

SMA
SMA

Reputation: 37023

You could do the same thing by ScheduledExecutorService

ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
s.schedule(myrunnable, 1000, TimeUnit.SECONDS);

To check for the file if any present. Altrenatively if you are allowed to use third party libraries, you could observe for changes in directories using FileAlterationObserver

Upvotes: 3

Related Questions