0

Is it safe to write from different threads to one file using FileChannel.position()? This is necessary for multipart downloading. Each thread will write to its position in the file, i.e. the positions of the thread will not intersect.

proninyaroslav
  • 720
  • 2
  • 7
  • 19

2 Answers2

2

While the individual option is thread safe, it's not thread local and changing it will be visible to all threads.

The simplest option is to create a FileChannel for each thread which avoid any interactions unless you write to the file in which case those changes can be seen.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Do I understand correctly that creating two different channels will allow me to safely move seek pointer for writing in the file? In other words, if the second thread moves seek pointer to the other position of the file, it will not be reflected in the first thread and first thread will continue to write data to the old position? – proninyaroslav Nov 18 '18 at 13:19
  • @proninyaroslav each FileChannel can point to a different position without interfering with each other. If each thread has it's own, they are only sharing the underlying file not the FileChannel. – Peter Lawrey Nov 18 '18 at 16:22
0

In the FileChannel Documentation, it says:

File channels are safe for use by multiple concurrent threads.

vollkorntomate
  • 638
  • 1
  • 8
  • 17
  • While the individual operation is thread safe, it's value is not thread local.and using it with other operations will result in race conditions. – Peter Lawrey Nov 18 '18 at 12:42