Search code examples
javataskexecutorsqueueing

Is it safe or advisable to re-enqueue a Runnable with the same Executor if a problem occurs and I want to retry?


I just wrote this code in my runnable's run() method:

try {
    dbConnection = MyApp.datasource.getConnection();
} catch (SQLException e) {
    logger.log(Level.SEVERE, "Could not obtain a DB connection! Re-enqueuing this task. Message: " + e.getMessage(), e);
    MyApp.executor.execute(this);
    return;
}

As you can see, if the task can't obtain a DB connection, it should re-enqueue itself, into the same queue it was in before it ran.

I'm thinking this is probably safe, but it feels funny, and I just want to make sure there aren't any gotchyas that I'm missing.

Thanks!


Solution

  • This is fine as far as the executor goes.

    But keep in mind that failures may occur pretty quickly, and then the Executor may re-run your code quickly. This can result in burning a lot of CPU for no results.

    Build in forced retry delays and maximum loop counts.