Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ExecutorService Infinite Loop Job

I am trying to write daemon service job in java. This service will run for every minute.

But I cannot implement this by using ExecutorService and I don't know if this is correct way. Below is my code snippet:

public void startService() {
    try {
        ExecutorService service = Executors.newFixedThreadPool(3);

        for (;;) {
            service.submit(new Service1()); // this will send some set of emails
            service.submit(new Service2()); // this will send some set of emails
            service.submit(new Service3()); // this will send some set of sms
        }
        service.shutdown(); // It says Unreachable code so when should i shutdown the service
        service.awaitTermination(1, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
like image 656
deadend Avatar asked Feb 06 '23 01:02

deadend


2 Answers

First you need to look at ScheduledExecutorService and its implementations. This service allows you to schedule the jobs to run with pre-defined frequency. This is the short answer. As for implementation details there are too many unknowns to give you practical advice. Do you want your program to run in a container (Web or Application Server) or as Standalone with domain thread? are you running on Unix/Linux (So the Cron job scheduler can be used) or Windows? One of the scheduler options could be quartz-scheduler. I hope this helps.

like image 90
Michael Gantman Avatar answered Feb 07 '23 17:02

Michael Gantman


Your for loop does not have an ending condition: for(;;), and no break statement.

So all the code after this loop is if course unreachable.


You have to wait 1 minute inside the loop, not after (as the code after your looping will never be runned).

Keeping your synthax, I guess it should be:

for (;;) {
    service.submit(new Service1()); // this will send some set of emails
    service.submit(new Service2()); // this will send some set of emails
    service.submit(new Service3()); // this will send some set of sms
    service.shutdown();
    service.awaitTermination(1, TimeUnit.MINUTES);
}
like image 23
Mistalis Avatar answered Feb 07 '23 19:02

Mistalis