I am working on a library in which I need to make synchronous and asynchronous methods in my client library.
My library does this:
The customer will use our library and they will call it by passing user_id
. We will then construct a URL by using that userId
and make an HTTP client call to that URL. We will then get a JSON string back after hitting the URL. And after we get the response back as a JSON string, then we will send that JSON String back to our customer as it is.
Now I need to have synchronous and asynchronous methods. Some customer will call the executeSynchronous
method to get the same feature and some customer will call our executeAsynchronous
method and with the executeAsynchronous
method, they will call future.get in there code itself.
Interface:
public interface Client {
// for synchronous
public String executeSynchronous(final String userId);
// for asynchronous
public Future<String> executeAsynchronous(final String userId);
}
And then I have SmartClient
which implements the Client
interface:
public class SmartClient implements Client {
private RestTemplate restTemplate = new RestTemplate();
private ExecutorService service = Executors.newFixedThreadPool(5);
// for synchronous call
@Override
public String executeSynchronous(String userId) {
String response = null;
try {
Future<String> handle = executeAsynchronous(userId);
response = handle.get(500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
}
return response;
}
//for asynchronous call
@Override
public Future<String> executeAsynchronous(String userId) {
Future<String> future = null;
try {
Task task = new Task(userId, restTemplate);
future = executor.submit(task);
} catch (Exception ex) {
e.printStackTrace();
}
return future;
}
}
This simple class will perform the actual task:
class Task implements Callable<String> {
private final String userId;
private RestTemplate restTemplate;
public Task(String userId, RestTemplate restTemplate) {
this.userId = userId;
this.restTemplate = restTemplate;
}
public String call() throws Exception {
String url = createURL(userId);
// make a HTTP call to the URL
String jsonResponse = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
return jsonResponse;
}
// create a URL
private String createURL(String userId) {
String generateURL = somecode;
return generateURL;
}
}
- Is this the correct and efficient way of solving this problem? Can we generalize my interface?
- How about the exception handling?
I need to have both synchronous and asynchronous methods so that the customer can call any method they like to call. Some customers might call the asynchronous method and then they will do future.get
in their own library. Some can call the synchronous method, which internally can call the asynchronous method and do a future.get
on it to return the response.
service
toexecutor
? \$\endgroup\$