File locking (read/write) in Java -


I am writing something to handle concurrent read / write requests in a database file.

It looks like a very good match. If all threads reach the shared object, do I need to worry about file pointer with concurrent readers? Consider this example:

  import java.io.FileNotFoundException; Import java.io.IOException; Import java.io.RandomAccessFile; Import java.util.concurrent.locks.ReentrantReadWriteLock; Public class database {personal fixed end-end RECORD_SIZE = 50; Private Stable Database Example = Faucet; Private Reentrant Redirect Lock Lock; Private RandomAccessFile database; Private Database () {Lock = New Reentrant Redirect Lock (); Try {database = new RandomAccessFile ("foo.db", "rwd"); } Hold (FileNotFoundException e) {e.printStackTrace (); }}; Public stable synchronized database getInstance () {if (example == zero) {example = new database (); } Return Example; } Public byte [] getRecord (int n) {byte [] data = new byte [RECORD_SIZE]; Try {// Important section Start the lock. Rolled lock (). Lock (); Database.seek (RECORD_SIZE * n); Database.readFully (data); Lock.readLock () Unlock ().; // last important segment} hold (IOException e) {e.printStackTrace (); } Return data; }}  

In the getRecord () method, is the low spacing possible with multiple concurrent readers possible?

thread 1 -> getRecord (0)
Thread 2 -> Miller Record (1)
Thread 1 -> Share Lock Receives
Thread 2 -> Share Receives lock
Thread 1 -> wants to record 0 - thread 2 -> wants to record 1 thread 1 -> reads the record on file pointer (1)
Thread 2 - > Reads the record on file pointer (1)

If there are actually possible concurrency problems, ReentrantReadWriteLock and RandomAccessFile, what would be an alternative?

Yes, this code is not properly synchronized, just as you have a read-write lock useful If written lock is never achieved; It seems like there is no lock.

The use of a conventional synchronized block for searching and reading appears atom on other threads, or RandomAccessFile such examples are same For the exclusive use of the thread, borrow and return (or just dedicate one channel to each thread, if you do not have many threads.)


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -