Re: Synchronous write to same file using different file pointers
- From: Leonard Milcin <leonard@xxxxxxxxxxxxxxxxxxx>
- Date: Tue, 29 Apr 2008 22:14:05 +0200
Alexander Dünisch wrote:
Hi newsgroup,
i have written a piece of code like the following:
// ======= start of code sample ===============
public void writeStuff(byte[] stuff, long location) throws IOException {
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
try {
raf.seek(location);
raf.write(stuff);
} finally {
raf.close();
}
}
// ======= end of code sample ===============
This function is being called by multiple threads.
Let's assume it can be guaranteed by the choice of value for location
and the length of array 'stuff', that one thread doesn't overwrite the bytes written by another thread.
Because the RandomAccessFile is local to the method,
each thread would create it's own instance and use the associated
file pointer.
Can this be done safely or do i have to put the call to write in a
synchronized block?
The answer isn't simple. For short writes under some specific number of
bytes (that will depend on the combination of OS/filesystem) you can
expect the writes to be atomic. I would recommend against using that
possibility. I'd write something to guard the access to that file that
would allow to queue writes that would then be performed synchronously.
Also, I don't think it's a good idea to open the file every time you
want to write something. Can't you just open the file (or the wrapper
class that would guard the access to the file) once, and then inject
that instance to all threads that want to use it?
In other words:
Can two or mor threads write synchronously to different locations of
the same file using different RandomAccessFile objects and thus
different file pointers, if there is no risk of one thread overwriting
another's data?
I've never done that but from what I know using NIO you can mmap a file
and then lock specific areas of that file before performing write
operations.
Thanks in advance for your answers.
You're welcome.
Regards,
Leonard
--
Simplicity is the ultimate sophistication.
-- Leonardo da Vinci
.
- Follow-Ups:
- References:
- Synchronous write to same file using different file pointers
- From: Alexander Dünisch
- Synchronous write to same file using different file pointers
- Prev by Date: my sql connectivity
- Next by Date: Re: GUI app freezing completely
- Previous by thread: Re: Synchronous write to same file using different file pointers
- Next by thread: Re: Synchronous write to same file using different file pointers
- Index(es):
Relevant Pages
|