Java:线程安全的RandomAccessFile [英] Java: thread-safe RandomAccessFile

查看:243
本文介绍了Java:线程安全的RandomAccessFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一些严肃的googleing后,我发现RandomAccessFile-class不是线程安全的。现在我可以使用一个信号量锁定所有读写但我不认为它表现得非常好。理论上,应该可以一次执行多次读取和一次写入。
我怎样才能用Java做到这一点?有可能吗?

After some serious googleing I found out that the RandomAccessFile-class is not thread-safe. Now I could use one semaphore to lock all reads and writes but I don't think that performs very well. In theory it should be possible to do multiple reads and one write at a time. How can I do this in Java? Is it possible at all?

谢谢!

推荐答案

部分锁定文件是一项复杂的业务,许多操作系统都避免这样做。但是,如果您坚持这样做,一种方法是设计自己的锁定机制对象,记录文件的哪些部分被锁定。基本上在读取或写入对象之前,必须请求锁定文件的特定字节范围。如果锁在字节范围内完全重叠,则认为它们会发生冲突。读写锁的处理方式不同:读取可以安全地与任意数量的读锁重叠,但写锁必须与其他锁,读或写重叠。如果你无法获得锁定,是否要等待或中止,以及是否在写入等待时阻止读取,有很多问题,但只有你可以回答它们关于你的应用程序。

Partial locking of a file is a complex business which a lot of operating systems avoid doing. However if you insist on doing it, one way is to design your own locking mechanism object that records which parts of the file are locked. Essentially before reading or writing an object must request a lock for a specific byte range of the file. Locks are considered to clash if they overlap at all in byte range. Read and write locks are treated differently: a read can overlap with any number of read locks safely, but a write lock must overlap with no other locks, read or write. There are a lot of questions about whether to wait or abort if you can't get the lock, and whether to block reads while a write is waiting, but only you can answer them about your application.

鉴于此复杂性,锁定整个文件可能更好。检查您是否获得足够的性能 - 并且不要忘记您可以一次允许多次读取,只要没有写入。

Given the complexity of this it may be better to lock the entire file. Check to see if you get adequate performance - and don't forget you can allow multiple reads at once, as long as there are no writes.

这篇关于Java:线程安全的RandomAccessFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆