Reading a file while it is being written

Overview

  • Topic 1 Trying to write some data to a file continuously
  • Topic 2 Trying to continuously read from a single file for analysis and data processing (read-only)

Problem:

  • In thread 2, the file size remains constant (this is not updated since Thread 1 is trying to write data to the file), and therefore I cannot parse the size of the original file.

Proven Things

  • A FileInputStream: . I tried to read from the input stream, the file size remains unchanged (122924 bytes) and never increases
  • RandomAccessFile: Same result as above, file size remains constant (122924 bytes), r / rw modes checked
  • FileChannel: I tried to work with the channel from FileInputStream, the same result as above
+4
source share
1 answer

You need to lock when you write or read a file. Thus, only one thread can access the file.

Here is the official Android site explaining the lock:

http://developer.android.com/reference/java/util/concurrent/locks/Lock.html

Here is an example of using a lock:

fooobar.com/questions/1541732 / ...

You can also use synchronization to lock the object, here it is explained:

Java sync

+1
source

Source: https://habr.com/ru/post/1541730/


All Articles