How to check invalid input case in the Asynchronous method?

I am working on a project in which I am supposed to make synchronous and asynchronous behavior of my client program. So I created an interface (IClient) which has two methods, one is getUserSync which is for synchronous behavior and other is getUserAsync which is for asynchronous behavior.

Below is my Client program which implements my interface (IClient) –

public class RedClient implements IClient {

    ExecutorService executor = Executors.newFixedThreadPool(5);

    @Override
    public RedResponse getUserSync(RedKey rdKeys) {

        // How to handle this case in getUserAsync method?
        if (RedUtils.isEmpty(rdKeys)) {
            return new RedResponse(null, RedClientError.INVALID_INPUT, RDClientStatus.ERROR);
        }

        RedResponse response = null;
        Future<RedResponse> handle = getHandle(rdKeys);

            try {
                response = handle.get(rdKeys.getTimeout(), TimeUnit.MILLISECONDS);
            } catch (TimeoutException e) {
                response = new RedResponse(null, RedClientError.TIMEOUT, RDClientStatus.ERROR);
            } catch (Exception e) {
                response = new RedResponse(null, RedClientError.ERROR, RDClientStatus.ERROR);
            }

            return response;
    }

    @Override
    public Future<RedResponse> getUserAsync(RedKey rdKeys) {

        // How to handle empty input keys case here just as I have handle it 
        // in getUserSync method

        return getHandle(rdKeys);
    }

    private Future<RedResponse> getHandle(RedKey beInput) {
        RedClientTask redClientTask = null;
        Future<RedResponse> future = null;

            try {
            RedClientTask = new RedClientTask(beInput);
            future = executor.submit(redClientTask);
            } catch (InterruptedException e) {

            }
        }

    return future;

    }
}

Now customer can call either getUserSync or getUserAsync method depending on there requirement. So in case of getUserSync method call, if they are passing Empty Input Keys, then I am making a response back that INVALID INPUT passed and returning it back..

Now how to do the same thing in getUserAsync method, as that method returns only Future so I am not sure how that is going to work out?

Answer

Throw an IllegalArgumentException in both cases; that’s what it’s for.

public Future<RedResponse> getUserAsync(RedKey rdKeys)  {
    if (RedUtils.isEmpty(rdKeys)) { 
        throw new IllegalArgumentException("rdKeys can not be empty");
    }
    ...
}

That said … I don’t see what the issue is. You’re returning a Future<RedResponse> … that’s a future that contains a RedResponse. In your getUserSync method you’re using a RedResponse to indicate the invalid input.

Leave a Reply

Your email address will not be published. Required fields are marked *