I need to create a library in which I will have a synchronous and asynchronous function.
executeSynchronous() - waits until I have a result, returns the result.executeAsynchronous() - immediately returns the Future, which can be processed after performing other actions, if necessary.
The main logic of my library
The client will use our library, and they will call it by passing the DataKey builder object. Then we will create a URL using this DataKey and make an HTTP client for that URL by executing it, and after we get the response as a JSON string, we will send this JSON string to our client, since this is created DataResponse object. Some clients will call executeSynchronous() , and some may call the executeAsynchronous() method, so I have to provide two methods separately in my library.
Interface:
public interface Client {
And then I have my DataClient that implements the above Client interface:
public class DataClient implements Client { private RestTemplate restTemplate = new RestTemplate(); private ExecutorService executor = Executors.newFixedThreadPool(10);
A simple class that will perform the actual task:
public class Task implements Callable<DataResponse> { private DataKey key; private RestTemplate restTemplate; public Task(DataKey key, RestTemplate restTemplate) { this.key = key; this.restTemplate = restTemplate; } @Override public DataResponse call() { DataResponse dataResponse = null; String response = null; try { String url = createURL(); response = restTemplate.getForObject(url, String.class);
A client in our company will use my library, as shown below, using my factory in its code base -
// if they are calling `executeSynchronous()` method DataResponse response = DataClientFactory.getInstance().executeSynchronous(dataKey); // and if they want to call `executeAsynchronous()` method Future<DataResponse> response = DataClientFactory.getInstance().executeAsynchronous(dataKey);
What is the best way to implement the sync and async method for my library? Does sync call as async + waiting implement a bad idea? Because it will consume one thread from the thread pool for each call with my setting in real time? If so, can anyone explain why this is a bad idea, and will it have any performance issues?
How will you apply the sync and async method, given the above criteria? What is the best way to do this? This library will be used under very heavy load, and it should be fast, that is, it should take the time my server responds.
Should I use AsyncRestTemplate in my code base, which will be an asynchronous non-blocking architecture?