views:

2809

answers:

8

Hi to all,

I have created a program which searches for files in a source folder. If it finds any file, it processes that file and moves it to a destination folder, then looks for a new file in the source folder. It has to keep on checking the source folder for a file.

I have used a thread to look for files in the source folder. The problem I am facing is whenever any exception is thrown during file processing, the thread gets stopped. I want the thread to be running even if an exception is thrown. It has to move the file that caused the error to some other folder and look for a new file in the source folder. How can I make the thread keep on running?

Eg:

public void run() {
    try {
        searchfile();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

public void searchfile(){
  ...
}
+11  A: 

If a thread is dying due to an uncaught exception, the answer is simple: catch the exception at an appropriate place so that you can keep going. Either catch the exception within your searchfile method, or make the run method call searchfile in a loop.

Jon Skeet
+1  A: 

Inside your catch, you can move the file to the error folder then create a new object of the same thread and start it again.

Bashar Kokash
+1  A: 

Thanks. But i should be more clear in my question. Actually there are 4 source folders and 4 destination folders. I have to perform the same operation in each source & destination pair. So i have created 4 threads in one class and do the operation in separate class.

class MainClass
{
public static void main(String[] args){
for(int i=0;i<4;i++){
SearchClass search = new SearchClass();
Thread thread = new Thread(search);
thread.start();
}
}
}

class SearchClass
{
public void run() {
try {
searchfile();
} catch(Exception e) {
e.printStackTrace();
}
}

public void searchfile(){ ... } }

All the thread wont stop running eventhough it caught any exception in middle. How can i do that?

raja
Please (!) provide this information in your QUESTION, not in an answer, because answers are still for ... answers :)
furtelwart
A: 

unless i got you wrong, your code is missing the "keep running" nature, i.e. you need to have a loop somewhere:

public static void main(String[] args){

    ExecutorService service = Executors.newFixedThreadPool(4);

    // for each of your 4 folders
    while (true) {
     Future<File> searchResult = service.submit(new SearchTask());
     try {
       File foundFile = searchResult.get();
       // handle found file
     } catch (Exception e) {
       // handle exception
     }
    }
}

private static class SearchTask implements Callable<File> {

    @Override
    public File call() {
      return searchFile();
    }

    public File searchFile() {
      // search & return found file
    }

}

note that this is just a very simple extension of your example. it is still missing the parametrization of the SearchTask to actually be specific for a folder, handling of files & exceptions, etc. as mentioned in previous answers, your SearchTask should implement Runnable (i prefer Callable...), and IMHO it's always better to use an ExecutorService than to spawn threads manually. hope this helps...

netzwerg
A: 

you said that the exception may be thrown during file process , so i put the processFile() in a try-catch block. but if it may be thrown during search, you may put it in a try-catch too.

public void run() {
    while(!terminated) {    
        findNextFile();
        try {
            processFile();
        } catch {
            // handle error
        }
    }
}
A: 

If you want your thread to keep running use a loop.

public void run() {
   while(!Thread.interrupted())
      try {
           searchfile();
      }
      catch(Exception e) {
          e.printStackTrace();
      }
}
Peter Lawrey
oops too slow but 11 hours!
Peter Lawrey
A: 

Here are my assumptions based on your question and your clarification:

  • Each thread, in the run() method, only calls searchfile() once and not in a loop
  • your searchfile() method has a loop in it and you want that loop to continue running even if an exception is thrown in it.
  • you have some way of initializing each thread that you aren't showing us (and that isn't terribly important for this specific quiestion)
  • searchfile() does not declare that it throws any Exception
  • You aren't using a logging framework, but are instead using System.out (although using a logging framework is a Really Good Idea
  • Java 5 is OK (otherwise you'll have to use a different for() loop below

With these assumptions, you don't want to plan to catch an Exception in your run() method except for the purpose of logging that something went very wrong:

public void run() {
    try {
        searchfile();
    } catch (RuntimeException e) {
        System.out.println("Something went very wrong!  Unexpected RuntimeException");
        e.printStackTrace();
    }
}

Note that the code catches RuntimeException. Always catch the most specific Exception that will do what you need. Then what you need is something such as the following in your searchfile() method:

File[] files = directory.listFiles();
for (File file : files) {
    try {
        // Do your normal file/directory processing here
    } catch (Exception e) {
        System.out.println("Exception processing file " + file.getName() + " " + e);
        // Move "file" to another area
    }
}

Since you are trapping unexpected Exceptions in the main loop of your Thread, your thread will continue processing after handling the Exception.

Eddie
A: 

I'm not entirely sure if this will work, yet here's a try.

public void run() {
    try {
        searchFile();
    } catch(Exeption e) {
        e.printStackTrace();
        if(!Thread.currentThread().isAlive())
            Thread.currentThread().start();
    }
}
John