tags:

views:

143

answers:

2

Hi to all,

I have created a program which search for a file in source folder. If it founds any file, it process that file and moves the file to destination folder and looks for new file in source folder. Like that it has to keeps on check the source folder for a file. I have used thread to look for files in source folder. Problem i am facing is whenever any exception throws during file process thread get stopped. I want the thread to be running even if the exception throws during file processing. It has to move that error to sum other folder and looks for for new file in source folder. How can i make thread to keeps on running?

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 search operation in second class and file processing in third 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 implements Runnable
{
   public void run() {
     try {
        searchfile();
     } catch(Exception e) {
        e.printStackTrace();
     }
   }

   public void searchfile(){
     try{
        ProcessClass p = new ProcessClass();
        p.fileProcess();
     }catch(Exception){
        e.printStackTrace();
     }
   }
}

class ProcessClass
{
    public void fileProcess(){
      try{
          .........................
          ...........  -----> 
          // Thread1 throws exception here and get stopped.
          // Its searching file in source folder again.
      }catch(Exception){
          e.printStackTrace();
      }
   }
}
+3  A: 

Isn't this a duplicate of this? http://stackoverflow.com/questions/468266/how-to-restart-thread-in-java

As Jon Skeet answered you there, Raja, you must learn exception handling.

artknish
+2  A: 

This has very little to do with threading, and everything to do with exception handling.

Your thread should probably be going through a loop:

  • Try to find a file in the source folder
  • If there isn't one, you're done (or possibly wait a while and try again)
  • Process the file
  • Catch any exceptions you understand, and take appropriate action - e.g. logging, moving the file to an "errors" folder, whatever
  • Go back to step 1
Jon Skeet