I am using Java Callable Future in my code. Below is my main code that uses the future and calling symbols -
Below is my main code that uses the future and defiant characters -
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 for my SERVERS using RestTemplate . And then I pass the response variable to the checkString method, in which I deserialize the JSON string and then check to see if it has the error or warning key in it, and then based on what make 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();
So my question is: how do I declare a GSON here? Should it be declared as a static final global variable in my Task class? Bcoz I'm currently parsing JSON using gson, and for every call I make new Gson() , which will be expensive or not?
java multithreading gson thread-safety
AKIWEB
source share