Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded access to file

We have a multi threaded java program. Multiple-threads will write to a file, and one thread will read from that file. I am looking for some design ideas. Is synchronization necessary?

like image 572
ravi Avatar asked Nov 19 '08 17:11

ravi


People also ask

Can file be accessed by multiple threads?

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface.

Can threads share files?

Resource sharing: Resources like code, data, and files can be shared among all threads within a process. Note: stack and registers can't be shared among the threads.


1 Answers

FileChannel is in theory thread safe. From the javadoc:

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the channel's position or can change its file's size may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations, in particular those that take an explicit position, may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified.

If you can use these, then you can use the built-in synchronization, rather than having to write your own.

like image 58
Bill Michell Avatar answered Sep 21 '22 05:09

Bill Michell