I am using Java Callable Future in my code. Below is my main code which uses the future and callables -
Below is my main code which uses the future and callables -
public class TimeoutThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<TestResponse> future = executor.submit(new Task());
try {
System.out.println(future.get(3, TimeUnit.SECONDS));
} catch (TimeoutException e) {
}
executor.shutdownNow();
}
}
Below is my Task
class which implements the Callable interface in which I am making a REST URL call to my SERVERS using RestTemplate
. And then I am passing response
variable to checkString
method in which I am deserializing the JSON string and then I am checking whether the key has error
or warning
in it and then basis on that make a TestResponse
.
class Task implements Callable<TestResponse> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public TestResponse call() throws Exception {
String url = "some_url";
String response = restTemplate.getForObject(url, String.class);
TestResponse response = checkString(response);
}
}
private TestResponse checkString(final String response) throws Exception {
Gson gson = new Gson(); // is this an expensive call here, making objects for each and every call?
TestResponse testResponse = null;
JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse, need to check whether it is an expensive call or not.
if (jsonObject.has("error") || jsonObject.has("warning")) {
final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
.get("warning").getAsString();
testResponse = new TestResponse(response, "NONE", "SUCCESS");
} else {
testResponse = new TestResponse(response, "NONE", "SUCCESS");
}
return testResponse;
}
So my question is how should I declare GSON
here? Should it be declared as static final global variable in my Task class? Bcoz currently I am parsing JSON using gson and for every call I am making new Gson()
which would be expensive or not?