2017-06-02 20 views
3

我正在使用球衣客戶端3.0快照。JerseyClient異步調用似乎離開掛線

我做這樣的事情:

final Client client = createClient(); 

...

Builder builder = target.request(); 
    for (final Entry<String, String> entry : getHeaders().entrySet()) { 
     builder = builder.header(entry.getKey(), entry.getValue()); 
    } 
    final Builder finalBuilder = builder; 
    executor.submit(() -> { 
     final Entity<?> entity = createPostEntity(); 
     futureResponse = finalBuilder.async().post(entity); 
     try { 
      response = futureResponse.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); 
      consumeResponse(response); 
     } catch (ExecutionException | TimeoutException | InterruptedException | IOException e) { 
      errorConsumer.accept(e); 
     } 
    }); 

    if (futureResponse != null) { 
     try { 
      futureResponse.cancel(true); 
     } catch (final Exception e) { 
      //does nothing, now we try keep closing resources 
     } 
    } 
    if (response != null) { 
     try { 
      response.close(); 
     } catch (final Exception e) { 
      //does nothing, now we try keep closing resources 
     } 
    } 

... //等待響應和閱讀或任何

client.close(); 

和一個新的線程保持每次出現創建並銷燬其中一個客戶。

有破壞這些線程的安全方法嗎? 這是預期的行爲? 我做錯了什麼?

回答

2

Jersey clientasynchronous電話,每當我們上client對象調用close(),它破壞了async呼叫使用的thread。因此,無論何時執行client.close()語句,它都會破壞該線程,並且下一次爲下一個async調用創建一個新線程。現在

,安全的方式來關閉client對象和相關的線程考慮誤差的情況一種是低於 -

Client client = ClientBuilder.newClient(); 

    WebTarget webTarget = client.target(SERVER_URL).path(API_PATH); 

    Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); 
    // set headers and other stuff 

    AsyncInvoker asyncInvoker = invocationBuilder.async(); 

    asyncInvoker.get(new InvocationCallback<Response>() { 

     @Override 
     public void completed(Response response) { 
      if (response.getStatusInfo().equals(Status.OK)) { 
       // parse the response in success scenario 
      } else { 
       // parse the response if error response is received from server 
      } 
      client.close(); 
     } 

     @Override 
     public void failed(Throwable throwable) { 
      System.out.println("An error occurred while calling API"); 
      throwable.printStackTrace(); 
      client.close(); 
     } 
    });