I am using Java Callable Future in my code. 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<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
Below is my Task
class which implements the Callable interface and I need to generate URL depending on the hostname we have and then make a call to SERVERS using RestTemplate
. If there is any exception in the first hostname, then I will generate URL for another hostname and I will try making a call.
class Task implements Callable<String> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public String call() throws Exception {
//.. some code
for(String hostname : hostnames) {
if(hostname == null) {
continue;
}
try {
String url = generateURL(hostname);
response = restTemplate.getForObject(url, String.class);
// make a response and then break
break;
} catch (Exception ex) {
ex.printStackTrace(); // use logger
}
}
}
}
So my question should I declare RestTemplate
as static global variable? Or it should not be static in this scenario?
It doesn't matter either way, static
or instance.
RestTemplate
's methods for making HTTP requests are thread safe so whether you have a RestTemplate
instance per Task
instance or a shared instance for all Task
instances is irrelevant (except for garbage collection).
Personally, I would create the RestTemplate
outside the Task
class and pass it as an argument to a Task
constructor. (Use Inversion of Control whenever possible.)