vendredi 9 décembre 2016

How to properly call asyncronous service witin syncronous method

I am client, that uses service.

I call method of service, that works asynchronously. Thats mean that method immediately returns some identifier(id), and then i should periodically check by this id, is task finished or not. For example, service provide three methods:

service.startTask(someData) //starts task and returns its id
service.isTaskFinished(taskId) // checks is task finished
service.getTaskResult(taskId) //returns task results

I need to realize method in java, that starts task, waits when task finished and then returns result of task. Only solution that i can imagine is about:

...
public Object invokeAsyncTaskAndGetResults(int someData) {

    int taskId = service.startTask(someData);

    int sleepTime = 1000;
    int maxCheckCount = 5;
    int hasResults = false;

    int i = 1;
    while (i <= maxCheckCount && !hasResults) {
        hasResults = service.isTaskFinished(taskId );
        i++;
        Thread.sleep(sleepTime);
    }

    if (!hasResults)
        throw new NotResultEcxeption(); //for exapmle, throw exception if task was not finished 

    Object result = service.getTaskResult(taskId);
    return result;
}
...

I want to ask you advice: is this pattern solution ok? Is using Thread.sleep() a good practice to periodically check task results? Or may be you can advice some frameworks for better solution?

Aucun commentaire:

Enregistrer un commentaire