我可以从不同的线程独立使用FileChannel寻找一个文件吗? [英] Can I seek a file from different threads independently using FileChannel?

查看:135
本文介绍了我可以从不同的线程独立使用FileChannel寻找一个文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个可用于FLV文件的web应用程序。



这个应用程序使用我创建的库来解析flv文件的内容。这个库使用FileChannel来寻找一个文件。

现在我遇到一个奇怪的行为,现在我从不同的线程寻找相同的flv文件。假设 Thread_1 Thread_2 都同时寻找 movie.flv (我的问题出现在示例之后)。

Thread_1

  // Thread_1移动到位置200 
FileChannel chan1 = new FileInputStream(movie.flv)。getFileChannel();
chan1.position(200);

Thread_2 (在 Thread_1 之后执行)

  // //线程2移动到位置600来读取其他内容
FileChannel chan2 = new FileInputStream(movie.flv ).getFileChannel();
chan2.position(600);

最后 Thread_1

  ByteBuffer bb = ByteBuffer.allocate(40); 
chan1.read(bb);

Thread_1 从位置200或位置600读取40个字节?
更确切的说,是独立的(=可以独立寻找)频道吗?



文档我读到FileChannel是 unique ,所以我打赌(不幸的是)在 Thread_1 将要从位置600读取:\



在这种情况下,你能否提出一种不同的方法来独立于不同的线程寻找一个文件?

谢谢!

解决方案

你很好,因为你在两个线程上都创建了一个新的FileInputStream。链接文档指出从FileInputStream.getChannel()返回的FileChannel对于该文件输入流是唯一
FileChannel的文档也表明,从不同源生成的不同FileChannel(例如不同的FileInputStream实例)将不共享状态。


I created a web application that works on FLV files.

This application uses a library that I created for parsing content from flv files. This library uses FileChannel to seek a file.

I'm experiencing a strange behavior now that I seek the same flv file from different threads. Let's say that Thread_1 and Thread_2 are both seeking movie.flv concurrently (my question comes after the example).

Thread_1

// Thread_1 moves to position 200 to read something
FileChannel chan1 = new FileInputStream("movie.flv").getFileChannel();
chan1.position(200);

Thread_2 (executing just after Thread_1)

// Thread_2 moves to position 600 to read something else
FileChannel chan2 = new FileInputStream("movie.flv").getFileChannel();
chan2.position(600);

Finally Thread_1 does:

ByteBuffer bb = ByteBuffer.allocate(40);
chan1.read(bb);

Is Thread_1 reading 40 bytes from position 200 or from position 600? More precisely, are chan1 and chan2 independent (=can seek independently) channels or not?

From the documentation I read that the FileChannel is unique, so my bet (unfortunately) is that in the example Thread_1 is going to read from position 600 :\

In case, can you suggest a different approach for seeking a file independently from different threads?

thanks!

解决方案

I think you're fine, since you're creating a new FileInputStream on both Threads. The linked documentation states that the FileChannel returned from FileInputStream.getChannel() is unique to that file input stream. The documentation of FileChannel also suggests that different FileChannels generated from different sources (e.g. different FileInputStream instances) will not share state.

这篇关于我可以从不同的线程独立使用FileChannel寻找一个文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆