You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅关闭Cumulocity测试客户端以终止JVM运行

如何优雅关闭Cumulocity Java客户端的开放连接以停止JVM?

我之前在使用Cumulocity Java SDK的时候也碰到过一模一样的问题——代码逻辑运行正常,但程序执行完毕后JVM就是无法自动停止,查线程栈发现是MultiThreadedHttpConnectionManager的后台线程还在存活。其实这是因为SDK默认的HTTP连接池会维持非守护线程来管理连接,JVM会等待这些线程结束才会退出,而默认情况下客户端不会主动关闭这些资源。

这里有两个优雅的解决办法:

方法1:使用try-with-resources自动管理Platform资源

Cumulocity的PlatformImpl类实现了AutoCloseable接口,所以可以把Platform的创建放在try-with-resources块中,这样当代码块执行完毕时,会自动调用close()方法,关闭所有底层的HTTP连接和线程:

try (Platform platform = new PlatformImpl(App.C8Y_URL, new CumulocityCredentials(App.C8Y_USER, App.C8Y_PWD))) {
    InventoryApi inventory = platform.getInventoryApi();
    GId testId = new GId("123456");
    ManagedObjectRepresentation testDevice = inventory.get(testId);
    
    MeasurementApi mApi = platform.getMeasurementApi();
    MeasurementRepresentation measurement = new MeasurementRepresentation();
    measurement.setType("c8y_SampleRate");
    measurement.setSource(testDevice);
    DateTime time = new DateTime();
    System.out.println("time " + time.toString());
    measurement.setDateTime(time);
    
    Map<String, Object> flowRateFragment = App.createFlowRateFragment(new BigDecimal(20.5));
    measurement.set(flowRateFragment, "c8y_SampleRate");
    MeasurementRepresentation measurementCreation = mApi.create(measurement);
} // 此处自动执行platform.close(),关闭所有连接池线程

方法2:手动调用close()方法关闭Platform

如果你的代码结构不适合用try-with-resources,也可以在所有业务代码执行完毕后,手动调用Platform的close()方法:

// 你的业务代码...
MeasurementRepresentation measurementCreation = mApi.create(measurement);

// 在代码末尾添加这行
platform.close();

这两种方法都会关闭底层的HTTP连接管理器,终止MultiThreadedHttpConnectionManager的后台线程,让JVM可以正常退出。

内容的提问来源于stack exchange,提问作者pmahler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:57:31