user7620991
user7620991

Reputation: 97

Running multiple threads concurrenty using ScheduledExecutorService

The below code executes a file transfer task periodically. I want to do another file copy task at same time from different location by calling the same method.For that i created another runnable2 and executor2 instances and executed. How to do multiple tasks using a single instance instead of creating multiple instances.

public static void main(String[] args) {

        Runnable runnable = new Runnable() {
          public void run() {

            File srcFolder = new File("c:\\location1\\Test1\\");
            File destFolder = new File("d:\\location1\\Test1\\");

            if(!srcFolder.exists()){
               System.out.println("Directory does not exist.");
               System.exit(0);
            }else{
               try{
                copyFolder(srcFolder,destFolder);
               }catch(IOException e){
                e.printStackTrace();
                System.exit(0);
               }
            }
            System.out.println("Done");           
            }
        };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);    
    executor.scheduleAtFixedRate(runnable, 0, 300, TimeUnit.SECONDS);
}

Upvotes: 1

Views: 1203

Answers (1)

Yazan
Yazan

Reputation: 6082

if you are going to do the same operation more than one time, then creating a class is better than anonymous class (make it have 2 params in constructor):

public class FileCopy implements Runnable {

    private String src="", dest = "";
    public FileCopy(String src, String dest){
        this.src  = src;
        this.dest = dest;
    }

    @override
    public void run(){
        File srcFolder = new File(src);
        File destFolder = new File(dest);

        if(!srcFolder.exists()){
           System.out.println("Directory does not exist.");
           //System.exit(0);
        }else{
           try{
            copyFolder(srcFolder,destFolder);
           }catch(IOException e){
            e.printStackTrace();
            //System.exit(0);
           }
        }
        System.out.println("Done"); 
    }//run
}

now you can make as many instances as you want, pass different params each time, and execute the Runnable

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);    
executor.scheduleAtFixedRate(new FileCopy(src1, dest1), 0, 300, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(new FileCopy(src2, dest2), 0, 300, TimeUnit.SECONDS);

Notes: :

  • may be you need to change this newScheduledThreadPool(1) to newScheduledThreadPool(2)? not so sure

  • System.exit(0); is not an option now, in case of errors, because you have multiple instances running, if one has a problem, that should not mean closing the whole app, you need to implement another way to handle errors

Upvotes: 1

Related Questions