Unidata / netcdf-java

The Unidata netcdf-java library
https://docs.unidata.ucar.edu/netcdf-java/current/userguide/index.html
BSD 3-Clause "New" or "Revised" License
146 stars 70 forks source link

Allow to pass CancelTask to Variable.read() or readAsync() method #639

Open laeubi opened 3 years ago

laeubi commented 3 years ago

I'd like to read a ucar.nc2.Variable (a big array) and like to monitor the progress of reading and allow the user to potentially cancel.

A ucar.nc2.util.CancelTask seems the supposed way, but read does not allow to specify one.

As an alternative I can think of to have a method readAsync() that returns a CompletableFuture, that would allow to cancel the future instead and the code can internally create a CancelTask for the future e.g. in the following way:

private CompletableFuture<Array> readAsync() {

    CompletableFuture<Array> future = new CompletableFuture<>();
    future.completeAsync(() -> {
        try {
            return proxyReader.reallyRead(Variable.this, new CancelTask() {

                @Override
                public void setProgress(String msg, int progress) {

                }

                @Override
                public void setError(String msg) {

                    future.completeExceptionally(new RuntimeException(msg));
                }

                @Override
                public void setDone(boolean done) {

                }

                @Override
                public boolean isDone() {

                    return future.isDone();
                }

                @Override
                public boolean isCancel() {

                    return future.isCancelled();
                }
            });
        } catch(IOException e) {
            future.completeExceptionally(e);
            return null;
        }
    });
    return future;
}
JohnLCaron commented 3 years ago

Thanks @laeubi this is a really good idea. Its a pretty deep change to make this work, but we will be considering how to do so.

laeubi commented 3 years ago

@JohnLCaron thanks for consideration. Moving away sync to async processing could really speedup things in some cases.