Search code examples
javamultithreadingasynchronousthreadpooljob-queue

Java Callback Execution in Thread Executed After run()


I'm using a job queue library, where you define Jobs and post them to a JobManager. The JobManager has a ThreadGroup with workers that pull Jobs off of a queue and call Job.onRun().

The amount of threads are set by giving a max and min amount of threads, a load factor (how many outstanding jobs can a worker thread have before creating a new one) and an idle timeout for any of the threads above min. Therefore, a worker thread's run() will terminate if it has no new jobs, and its idle timeout is reached.

In some Jobs I'm using libraries that only expose an async API. Is it safe to use these in onRun()?

For example, if I want to make a network request that takes a callback which provides me with a response will the callback get called:

@Override
public void onRun() throws Throwable {
    client.doRequest(request, new Callback() {
        @Override
        public void onRequestComplete(Response response) {
            //is this guaranteed to get called?
        }
    });
    //since we now return from onRun() will onRequestComplete() get called?
}

Solution

  • It is safe to do as long as you know that the following are true (while the process is alive):

    1. Every Job's onRun() method will always be executed (eventually), and
    2. Every async API that you use will always call its callback method (even when there are exceptions).