【发布时间】: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