posted 23 years ago
Rong,
You seem to be making the assumption that synchronizing access to all code that modifies the db is sufficient. I decided not to go with that assumption for several reasons: 1) Sun specifically mentioned in my instructions that I was to implement lock() and unlock, 2) Sun mentioned the sequence "lock, read, modify, write, unlock", which implies that the record should remain locked between lock() and unlock() calls, not just while the client is in a single data modification method, and 3) I don't like the idea of a server trusting clients to behave appropriately.
I'll elaborate on #3: If you trust clients to behave, and never call a modification method without first calling lock(), you can just have the modification methods reject any calls unless lock() has been called for that record and unlock() hasn't. If you don't trust them (I don't - who knows what kind of future clients might be written?) then the modification methods must somehow verify that the client calling them is the one with the lock, or one client could lock a record and another one (the bad boy) could modify it.
A final note: The instructions from my assignment say "Record locking must be implemented using the methods public void lock(int) and public void unlock(int)", but they don't say you have to implement them in Data. I don't want to be explicit, but that should hint at one possible solution.
I'm not sure what you mean when you say "let the jvm do synchronization for each locker". Are you thinking about grabbing a synchronization lock in lock() and keeping it until unlock()? How would that work? The sync lock would be relinquished when the lock() method returns. Also remember that, at least in an RMI server, you can't depend on all requests from a single client being handled in the same thread. What if RMI placed the client's modify() call in a different thread than its lock() call? Can you elaborate on what you're thinking about?
As to whether to use a queue, I eventually decided not to do that, but it's a good idea. I decided that the server could handle requests fast enough that the delay any client experienced from random lock granting would be small compared to network latency, unless the number of simultaneous clients was huge. But a queue (per lock) would make the server behave more correctly.
Hope this discussion helped, or at least was entertaining.
Jerry