Search code examples
javamultithreadingtimerexecutor

Execute multiple threads each one for a certain amount of time in java


I'm sending files to my local server that creates a file back. My problem occurs when the user perform multiple actions one after another and I need to show an error message if one of the requests don't get a feedback file in 5 min.

How can I handle all these requests? I used newSingleThreadScheduledExecutor to check if the feedback file is there every minute but I don't know how to handle multiple ones and keep the countdown to each request for the 5 min case. My try:

ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(listPrinter.size()));
        for(int i=0;i<list.size();i++){
            try {

                final File retrievedFile = new File("/home/"+list.get(i)+".csv");

                ListenableFuture<File> future = executor.submit(new Callable<File>() {
                    public File call() {
                        // Actually send the file to your local server
                        // and retrieve a file back

                        if(retrievedFile.exists())
                        {
                            new Notification("file exits").show(Page.getCurrent());
                        }
                        else{
                            new Notification("file no exits").show(Page.getCurrent());
                        }
                        return retrievedFile;
                    }
                });
                future.get(5, TimeUnit.MINUTES);
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            } catch (ExecutionException ex) {
                Exceptions.printStackTrace(ex);
            } catch (TimeoutException ex) {
                Exceptions.printStackTrace(ex);
                new Notification("Time out").show(Page.getCurrent());
            }
        }

But it just get executed at the beginning and that's it but when the file is added nothing happens.

Is it possible to do this with watchService? It works pretty well for me but I didn't know about the 5 min case


Solution

  • I solved the problem by using a Timer that is executed every 5 minutes getting all the db transactions that happened for the last 5 minutes and didn't get any response and show my error code. It works pretty good. Thanks everyone for the help