Databases Reference
In-Depth Information
But what happens when two processes try to deliver messages at the same time to the
same mailbox? Clearly that could corrupt the mailbox, leaving two interleaved mes-
sages at the end of the mailbox file. Well-behaved mail delivery systems use locking to
prevent corruption. If a client attempts a second delivery while the mailbox is locked,
it must wait to acquire the lock itself before delivering its message.
This scheme works reasonably well in practice, but it gives no support for concurrency.
Because only a single process can change the mailbox at any given time, this approach
becomes problematic with a high-volume mailbox.
Read/Write Locks
Reading from the mailbox isn't as troublesome. There's nothing wrong with multiple
clients reading the same mailbox simultaneously; because they aren't making changes,
nothing is likely to go wrong. But what happens if someone tries to delete message
number 25 while programs are reading the mailbox? It depends, but a reader could
come away with a corrupted or inconsistent view of the mailbox. So, to be safe, even
reading from a mailbox requires special care.
If you think of the mailbox as a database table and each mail message as a row, it's easy
to see that the problem is the same in this context. In many ways, a mailbox is really
just a simple database table. Modifying rows in a database table is very similar to re-
moving or changing the content of messages in a mailbox file.
The solution to this classic problem of concurrency control is rather simple. Systems
that deal with concurrent read/write access typically implement a locking system that
consists of two lock types. These locks are usually known as shared locks and exclusive
locks , or read locks and write locks .
Without worrying about the actual locking technology, we can describe the concept as
follows. Read locks on a resource are shared, or mutually nonblocking: many clients
can read from a resource at the same time and not interfere with each other. Write
locks, on the other hand, are exclusive—i.e., they block both read locks and other write
locks—because the only safe policy is to have a single client writing to the resource at
a given time and to prevent all reads when a client is writing.
In the database world, locking happens all the time: MySQL has to prevent one client
from reading a piece of data while another is changing it. It performs this lock man-
agement internally in a way that is transparent much of the time.
Lock Granularity
One way to improve the concurrency of a shared resource is to be more selective about
what you lock. Rather than locking the entire resource, lock only the part that contains
the data you need to change. Better yet, lock only the exact piece of data you plan to
 
Search WWH ::




Custom Search