java - 如何设计一个Java库的大量I/O进程的可取消API?
问题描述
EDIT_2:这个问题的目的是
当 API 有更多逻辑(例如:更多 I/O 或网络连接)时,我们不需要在这些 I/O 或网络逻辑中插入布尔标志条件来知道它是否被取消。
EDIT_1:我将术语中断更改为取消以避免混淆线程的中断概念。
抱歉误导。
我有一个现有的 API,它有很多 IO 进程。例如
void heavyTask() {
// Download File #1 with Network I/O
HttpClient client1 = new HttpClient()
....
...
..
while() {
outputStream1.write()
}
// Save File #1 with File I/0
File file1 = new File();
....
...
..
// Download File #2 with Network I/O
HttpClient client2 = new HttpClient()
....
...
..
while() {
outputStream2.write()
}
// Save File #2 with File I/0
File file2 = new File();
...
..
}
我的想法是通过检查 HeavyTask() 中的取消标志来添加取消 API
volatile isCancelled = false;
void cancelHeavyTask() {
isCancelled = true;
}
void heavyTask() {
// Download File #1 with Network I/O
HttpClient client1 = new HttpClient()
....
...
..
while() {
outputStream1.write()
if (isCancelled == true) // Add isCancelled flag
return;
}
// Save File #1 with File I/0
File file1 = new File();
....
...
..
if (isCancelled == true) // Add isCancelled flag
return;
// Download File #2 with Network I/O
HttpClient client2 = new HttpClient()
....
...
..
while() {
outputStream2.write()
if (isCancelled == true) // Add isCancelled flag
return;
}
// Save File #2 with File I/0
File file2 = new File();
...
..
if (isCancelled == true) // Add isCancelled flag
return;
}
目前标志方式有效,但我可以预期当heavyTask变得更加复杂时会有更多的“检查标志条件”。
我还想创建一个特定的工作线程来处理heavyTask,并在触发取消时调用工作线程的thread.interrupt() 。
但是,在对网络 I/O 案例进行了一些调查之后,似乎它在执行网络 I/O 进程时仍然阻塞,甚至触发了 thread.interrupt()。也许 thread.interrupt() 不是一个好的实现方式。
是否有一种简洁而智能的方法来设计可取消的重任务 API?
谢谢
解决方案
推荐阅读
- google-cloud-platform - 如何使用 sql 在 BigQuery 表中查找缺失的日期
- powershell - 使用一个查询的结果作为命令的参数(在单行上)
- php - 使用自定义端口连接数据库 Codeigniter 4
- powerbi - 获取过滤值和总数的百分比
- html - html和html有什么区别?
- python-3.x - 如何获取从 HTTP 触发的 Google Cloud Functions 的执行 ID?
- ios - 找不到选项“-L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0/iphonesimulator”的目录
- flutter - Flutter 错误:在 null 上调用了方法“验证”。接收方:null 尝试调用:validate()
- flutter - 底部溢出 55 个像素的 RenderFlex (Android)
- python - Pandas 导致 EXE 文件(使用 PyInstaller)具有巨大的大小(几乎 0.5 GB)