【问题标题】:How to eliminate race condition in Rox NIO tutorial如何在 Rox NIO 教程中消除竞争条件
【发布时间】:2014-12-05 00:22:47
【问题描述】:

我一直在使用this 教程,这是一个使用套接字 IO 的简单文件传输客户端/服务器。我将响应处理程序更改为接受多个读取作为一个文件的一部分,因为我将处理大文件,可能高达 500 MB。该教程没有考虑大型服务器响应,所以我有点挣扎,我创建了一个竞争条件。

这是响应处理程序代码:

public class RspHandler {

private byte[] rsp = null;
public synchronized boolean handleResponse(byte[] rsp) {
    this.rsp = rsp;
    this.notify();
    return true;
}

public synchronized void waitForResponse() {
    while(this.rsp == null) {
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }
    System.out.println("Received Response : " + new String(this.rsp));
}

public synchronized void waitForFile(String filename) throws IOException {
    String filepath = "C:\\a\\received\\" + filename;
    FileOutputStream fos = new FileOutputStream(filepath);
    while(waitForFileChunk(fos) != -1){}
    fos.close();
}

private synchronized int waitForFileChunk(FileOutputStream fos) throws IOException
{
    while(this.rsp == null) {
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }
    fos.write(this.rsp);
    int length = this.rsp.length;
    this.rsp = null;
    if(length < NioClient.READ_SIZE)//Probably a bad way to find the end of the file
    {
        return -1;
    }
    else
    {
        return length;
    }

}
}

程序的主线程在主线程上创建一个RspHandler,并将它传递给一个客户端,在一个单独的线程上创建。主线程告诉客户端请求一个文件,然后告诉 RspHandler 监听响应。当客户端从服务器读取时(它现在读取大约 1KB 的块),它调用 handleResponse(byte[] rsp) 方法,填充 rsp 字节数组。

本质上,我不会将接收到的数据尽快写入文件。我对线程有点陌生,所以我不确定该怎么做才能摆脱这种竞争状况。有什么提示吗?

【问题讨论】:

    标签: java nio race-condition


    【解决方案1】:

    这是典型的消费者/生产者。处理此问题的最直接/最简单的方法是使用 BlockingQueue。生产者调用put(),消费者调用take()

    注意,使用 BlockingQueue 通常会导致“我如何完成”问题。最好的方法是使用“毒丸”方法,其中生产者在队列上粘贴一个“特殊”值,向消费者发出没有更多数据的信号。

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      相关资源
      最近更新 更多