mercredi 6 mars 2019

How to handle dependent async operations in a domain class (Java)?

I've got a class which has some operations dependent on each other.

class MyFile{

    private String uploadedUri;

    public void upload(){
        // http upload
    }

    public void asyncUpload(){
        // http async upload
    }    

    public void convert(){
        //http call to convert
    }

    public void convertAsync(){
        //http call to convert, but async
    }

    public void extract(){
        //http call to convert, but async
    }

    public void extractAsync(){
        //http call to convert, but async
    }


    // some other operations


}


Now, my convert operation depends on upload, it only acts on the uploaded URI. In the sync convert, I check if the uri is set. If not, I'll first upload it. Similarly, there are other methods (extract for example) in the class which depend on the convert method, i.e. if the conversion is not done, they'll attempt to convert it. This is being done so that the caller of the methods doesn't have to worry about the order.

My problem is with the async methods. When the sequence of methods is like this:

MyFile myfile = new MyFile();
myfile.convertAsync()
myfile.extractAsync()

Inside the extractAsync(), I can't be sure if the conversion has taken place, since it's happening in a separate thread. So the extract will start the conversion as well, which will lead to conversions for the file. The same problem arises in any of the other dependent asycn methods.

If I return CompletableFuture from the async methods, and force the user to chain the operations, so that extract is only called after convert has completed, the user has to know the order of the methods, which defeats my purpose, and is different than the sync implementation of the same methods.

I want to know if this is the right way of handling dependent operations in a domain class as per DDD. If yes, how to handle this scenario?

Aucun commentaire:

Enregistrer un commentaire