Home > Software design >  ScheduledExecutorService not working as expected
ScheduledExecutorService not working as expected

Time:02-02

On executing the following code, the statement System.out.println("completed"); gets executed before the executor even though delay is set to 0. Why is it so? How can the order be maintained here?

public class TestMyClass {
    private static int count = 0;

    public static void main(String args[]) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        Runnable periodicTask = () -> {
            try {
                List<String> lines = Files.readAllLines(new File("E:\\MyFile.log").toPath());
                String key = "FIND ME";
                System.out.println("text not found");
                for (String line : lines) {
                    if (line.contains(key)) {
                        count  ;
                        System.out.println("found text ..."   count);
                        executor.shutdown();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        executor.scheduleAtFixedRate(periodicTask, 0, 5, TimeUnit.SECONDS);
        System.out.println("completed");
    }
}

CodePudding user response:

Checking the condition while(!executor.isTerminated()) does the job. It ensures the next statements are executed only after the executor has done its job.

CodePudding user response:

The reason is in the nature of multi-tasking/threading. The ScheduledExecutorService starts a new thread that executes your Runnable. Independently from that your main program continues its work in its own/original thread.

Both threads, the main and the runnable, will be processed in parallel.

In your case, the System.out.println("completed"); is faster in the execution then the Runnable that reads a file.

Now it depends on what you want to achieve. As you wrote already you can block your main program, e.g. with a loop and wait for the executor to finish all execution. But this is not what you usually do because then you could just execute the code in the same thread.

Typically you use multi-threading to execute code in parallel or to not block a task/thread, e.g. calling an web service and continue to do some other stuff.

  • Related