2014-02-11 40 views
8

我在我的代碼中使用Java Callable Future。下面是使用未來,可調用我的主要代碼 -應該將GSON聲明爲靜態最終?

下面是一個使用未來可調用我的主要代碼 -

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(); 
    } 
} 

下面是我Task類,它實現可調用接口中,我想提出使用RestTemplate向我的SERVERS發送REST URL調用。然後我通過response變量爲checkString方法,其中我反序列化JSON字符串,然後我檢查密鑰是否有errorwarning在其中,然後根據那個作出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; 
} 

所以我的問題是我應該如何在這裏聲明GSON?它應該在我的Task類中聲明爲靜態最終全局變量嗎? Bcoz目前我正在使用gson解析JSON,並且對於每次致電new Gson(),這會很昂貴或不是?

+0

請參閱http://stackoverflow.com/questions/10380835/is-it-ok-to-use-gson-instance-as-a-static-field-in-a-model-bean-reuse – Vadzim

回答

13

Gson對象在多線程中顯式安全使用,因爲它不保留任何內部狀態,所以是的,聲明一個private static final Gson GSON = new Gson();,或者甚至使它成爲public

請注意,如果您希望您的客戶端代碼能夠使用GsonBuilder自定義渲染,則應該接受Gson對象作爲參數。

+2

+1 :這是關於在json操作期間沒有維護任何狀態的官方字眼https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson – PopoFibo

+0

@PopoFibo找到了確切的段落並滾動正確的過去... – chrylis

+0

@chrylis:你可以解釋你的第二點GsonBuilder,因爲我以前沒有使用它,所以不知道這一點。或者如果你可以提供一個例子,那麼它會有很大的幫助。 – AKIWEB

0

Gson庫可以在類級別定義並在各處使用,因爲它不會在不同的調用之間維護狀態。由於它不保持狀態,因此可以聲明一次並在任何地方使用它(如果需要重用它,則少用一行代碼)。多線程對它沒有影響。 但是,在另一個說明中,從官方文檔看它的性能指標,它似乎並不昂貴。