Java 中如何限制方法的返回时间
2023-03-07 09:05:55 时间
最近在研究 ChatGPT 的 API 调用。
因为 ChatGPT 的 API 调用时间通常超过 30 秒。
所以我们希望在程序中限制这个方法的执行时间,不要让方法花太长时间去执行了。
JDK 方法
可以使用 JDK 中的 ExecutorService 方法来对调用的方法进行处理。
代码如下:
ExecutorService executor = newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public String call() {
return callChatGPT(content);
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(15, TimeUnit.SECONDS);
contentGPT = (String) result;
} catch (TimeoutException ex) {
contentGPT = "ChatGPT API Time out, Please Re-try it";
} catch (InterruptedException e) {
contentGPT = "ChatGPT API Time out, Please Re-try it";
} catch (ExecutionException e) {
contentGPT = "ChatGPT API Time out, Please Re-try it";
} finally {
future.cancel(true); // may or may not desire this
}
在我们的调用方法 callChatGPT 中,我们配置了一个 ExecutorService 执行器。
在这个执行器中,我们配置一个任务。
然后这个任务我们指定了执行时间为 15 秒。
如果这个方法的执行时间超过了 15 秒,程序将会抛出一个异常。
可以通过这个方法来限制方法的执行时间。
相关文章
- Java要抛弃祖宗的基业,Java程序员危险了!
- 十大 Java 语言特性
- JVM 三色标记算法,原来是这么回事!
- 聊聊 Spring 事务控制策略以及 @Transactional 失效问题避坑
- 写给 Java 程序员的前端 Promise 教程
- 写给 Java 程序员的前端 Promise 教程,你学会了吗?
- Java 中为什么不全部使用 Static 方法?
- Java 池化技术你了解多少?
- Java 服务 Docker 容器化优秀实践
- Spring Boot + EasyExcel导入导出,简直太好用了!
- 我们一起聊聊 Java 内存泄漏
- CentOS 下安装 Docker 极简教程
- JDK 19 功能集冻结:Java 19 只有七个新特性
- 关于 CMS 垃圾回收器,你真的懂了吗?
- 为什么会有这么多编程语言?
- 改善Java代码的八个建议
- 接口流量突增,如何做好性能优化?
- Java 以编程方式创建JAR文件
- POJO、Java Bean是如何定义的
- Spring 的 Bean 明明设置了 Scope 为 Prototype,为什么还是只能获取到单例对象?