ListenableFutures and the Scheduler

Good day,

The Guava library provides some useful tools, such as ListenableFutures, that greatly improve and simplify asynchronous task management.

On vanilla Bukkit, scheduling a task that retrieves information asynchronously then schedules a synchronous task that uses said information can sometimes make code not quite as good looking. But with Guava’s Futures class, one can simply add a callback which will easily execute something for you once an asynchronous task is done.

For example, the following code can become difficult to read, especially when you need to do it multiple times…

runAsyncTask(new Runnable() {
    try {
        final String x = getSomeData();
        runSyncTask(new Runnable() {
            void run(){
                getLogger().info(x);
            }
        });
    } catch (final SomethingTerrible e) {
        runSyncTask(new Runnable() {
            void run(){
                getLogger().info(e.getMessage());
            }
        });
    }
});

To improve the readability and flexibility, one could instead do…

ListenableFuture<String> ft = runAsyncTask(new Callable<String>(){
    String call() throws Throwable{
        return getSomeData();
    }
});
Futures.addCallback(ft, new FutureCallback<String>(){
    void onSuccess(String result) {
        getLogger().info(result);
    }
    void onFailure(Throwable t){
        getLogger().severe(t.getMessage());
    }
}, getSyncExecutorRef());

This does, of course, contain pseudocode

I was curious to know if Sponge’s scheduler could make use of the ListenableFuture and accompanying classes/interfaces. I’ve not really seen too much attention given to these utilities and believe that they could be of great use. Now, I’ve not really seen too much discussion (recently) relating to the scheduler system, so I may be going far off from what you all had planned, though I believe that adding such functionality will make us developers’ lives easier.

I’ve forked SpongeAPI and added a rough-draft of my idea, and I’ll make a PR if it gets good attention here!

Thanks for your consideration,

  • PieGuy

Looks good. I’ve never looked into the Guava library before.