5

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!

Community
  • 1
  • 1
Giordano
  • 1,401
  • 15
  • 26

3 Answers3

4

I have written a library which supports writing and reading from the same file, in different threads or different processes. It works just fine (provided the stream is only use by one thread)

You might find memory mapping the file is a simpler way to share the data as the entire file is notionally in memory. You can create multiple .splice() of the MappedByteBuffer to access it in different places concurrently (one per thread). It will also be up to 10x faster than making a system call.

Eugene
  • 117,005
  • 15
  • 201
  • 306
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • thanks for the suggestion. In my case however there are several threads accessing the file concurrently (in read mode). I'll also have a look for sure on splice(). Thanks and vote up! – Giordano Feb 03 '12 at 22:37
1

FileChannel instance is unique for it's source stream instance. There are two different FileInputStream instances in your example. So i think their channels are not depend on each other.

lxbndr
  • 2,159
  • 1
  • 15
  • 17
0

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.

texclayton
  • 189
  • 1
  • 4