Java – ‘AsyncExecutor’ means to execute one ‘AsyncTask’ at a time, sometimes two at the same time

‘AsyncExecutor’ means to execute one ‘AsyncTask’ at a time, sometimes two at the same time… here is a solution to the problem.

‘AsyncExecutor’ means to execute one ‘AsyncTask’ at a time, sometimes two at the same time

AsyncExecutor

I have a AsyncExecutor is defined as follows:

asyncExecutor = new AsyncExecutor(1);

The constructor for AsyncExecutor is

AsyncExecutor(int maxConcurrent), and maxExecutor is how much AsyncTask s allow to run side-by-side at a point in time. If set to 1, all AsyncTasks should be run, which are included in the order in which they were added.

AsyncTask

I’m implementing an interface on a class I'm creating that handles a set of logic that needs to be run one by one in their order submit to AsyncExecutor — by calling submit Methods on AsyncExecutor:

private class Foo implements AsyncTask<Object>
{
    // ...

public Foo()
    {
         Transfers variables over
    }

@Override
    public Object call() throws Exception
    {
        System.out.println("Start");

 Does some stuff here

System.out.println("Stop");

return null;
    }
}

Then I submit these foo on asyncExecutor every once in a while and ask them to run sequentially from the time they are added. This is the case most of the time, but let’s look at the console output – every once in a while, this is not the case :

...
Start
Stop
Start
Stop
Start
Start
Stop
Start
Start
Stop

Is there anything I missed? This should obviously never state “start” in two lines next to each other, nor “stop” in this matter.

Maybe someone can point me in the right direction?

Solution

I think you have an uncaught exception in the AsyncTask implementation. Because there is no exception barrier in your AsyncTask.call implementation, the thread will die on attempt. That’s why you appear multiple times instead of Stop.

You can add some parameters to your System.out.println() as an indication to see if this happens.

As a solution, just add some try-catch with print lines to your Foo class for Throwable.

Example I used for testing:

public static void main(String[] args) throws InterruptedException {
    AsyncExecutor asyncExecutor = new AsyncExecutor(1);
    for (int i = 0; i < 100; i++) {
        asyncExecutor.submit(new Foo(i));
    }
    Thread.sleep(10000);
}

static class Foo implements AsyncTask<Object>
{

private int i;

public Foo(int i) {
        this.i = i;
    }

@Override
    public Object call() throws Exception
    {
        try{
            System.out.println("Start" + i + "/" + Thread.currentThread().getName());

if((this.i % 9) == 0){
                throw new Exception("Ugly.");
            }

System.out.println("Stop " + i + "/" + Thread.currentThread().getName());

} catch (Throwable t){
            t.printStackTrace();
        }
        return null;
    }
}

Related Problems and Solutions