首页 > 解决方案 > 如何设计一个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?

谢谢

标签: javamultithreading

解决方案


推荐阅读