Search code examples
executorservicescheduledexecutorservice

Schedule task execution, but don't block callers


What is the correct way to schedule a task to be executed, but not block calling thread.

Is this the correct way of doing so?

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Main {

    public static void main(String [] args) throws ExecutionException, InterruptedException {
        final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        ScheduledFuture<?> f = service.schedule(new Runnable() {
            public void run() {
                System.out.println("Before sleep");
                try {
                    Thread.sleep(50000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("After sleep");
            }
        }, 0, TimeUnit.MINUTES);

        try {
            f.get(0, TimeUnit.MINUTES);
        } catch (TimeoutException e) {
            //
        }


        System.out.println("Main thread");
    }
}

As far as I understand if I just call f.get(), then it will block calling thread till the completion of future. What I am trying to do is to submit the tasks, but do not block caller threads.


Solution

  • Calling f.get() will block only if the task hasn't finished yet. If the task is finished, it will just return its result without blocking.

    If you don't care about the result and just want to run some tasks, simply ignore the Future returned by schedule().