ดูเหมือนว่าการโทร async ของ JerseyClient จะปล่อยให้เธรดค้าง

ฉันใช้ jersey-client-3.0-SNAPSHOT

ฉันทำบางอย่างเช่น:

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

และเธรดใหม่จะปรากฏขึ้นทุกครั้งที่สร้างและทำลายหนึ่งในไคลเอนต์เหล่านั้น

มีวิธีที่ปลอดภัยในการทำลายเธรดเหล่านั้นหรือไม่? นี่เป็นพฤติกรรมที่คาดหวังหรือไม่ ฉันกำลังทำอะไรผิดหรือเปล่า?


person eduyayo    schedule 02.06.2017    source แหล่งที่มา


คำตอบ (1)


ในการเรียก asynchronous ใน Jersey client เมื่อใดก็ตามที่เราเรียก close() บนอ็อบเจ็กต์ client มันจะทำลาย thread ที่ใช้ในการเรียก async ดังนั้นจึงเป็นพฤติกรรมที่คาดหวังไว้ว่าเมื่อใดก็ตามที่คำสั่ง 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();
        }
    });
person Vikas Sachdeva    schedule 10.06.2017