I am working on the URLyBird assignment. My interface contains the following two signatures
// Reads a record from the file. Returns an array where each // element is a record value. public String read(int recNo) throws RecordNotFoundException;
// Returns an array of record numbers that match the specified // criteria. Field n in the database file is described by // criteria[n]. A null value in criteria[n] matches any field // value. A non-null value in criteria[n] matches any field // value that begins with criteria[n]. (For example, "Fred" // matches "Fred" or "Freddy".) public int find(String criteria);
I use a locking mechanism that uses a static hashmap in my data class that contains the recordNo of a locked record and an object that is used to synchronize on the record. I then test if a record is locked by looking in the hashmap. I do this any time a write action is performed.
My question is should the read and find methods above also be made thread safe. For example lets say client a performs a search by calling find and his search returns a record with record number =1. However at the same time client b has this same record locked, should this record be returned to the client even though it is locked? Within my find method I create a new RandomAccessFile Object that I use to iterate through the all of the records checking if a record meets the specified search criteria until EOF is reached.
SCJP, SCJD, SCWCD, SCBCD
author and jackaroo
Your code does need to be thread safe, but that does not necessarily imply that a client cannot search for, or find, a record while it is locked.
Depending on how you write your code, you may have multiple threads running the same or different methods simultaneously.
But the purpose of logical record locking (using the lock() and unlock() methods) is that it allows you to have other processing happening (such as validating your record) without causing blocking.
All you need to do is ensure that while an individual record is being updated, you do not allow any other thread to access the record. You can therefore reduce your blocking to a much smaller interval.