The posts in this forum are very enlightening. I have been thinking about the locking issue the whole morning today. I would like to share my thoughts and hope that you guys can advise on them.
If there is only one Data object on the server side processing all database requests, then the readRecord(long recNo) method must be synchronized. Otherwise, the local variable recNo may be changed by another client before the method completes. That is, if the server spawns multiple threads to handle multiple concurrent client requests, and these threads call methods on the same Data object, even reads need to be synchronized. This approach is not the most efficient.
Similarly, since createRecord(String data) does not require a lock cookie, it's possible that client 1 is trying to read while client 2 tries to create a new record. This scenario also requires readRecord(long recNo) be synchronized.
Now, suppose the server spawns a new thread for each client request, and each such thread creates a new Data object to work with the database. My understanding of synchronization is that each thread will have its own separate copy of a Data object on its stack. Therefore, keyword synchronized will not work on non-static methods. In other words, thread A calling a synchronized method doesn't prevent thread B from acquiring a lock on its Data object. Thus, both threads may modify the database at the same time.
I realized that the locking that should be achieved in this assignment is data protection on the database file. Concurrent reads should be allowed while concurrent writes should not be allowed. If there are reads happening, write requests give up CPU and wait, and vice versa.
My pesuedo solutions is that each client request is handled by a separate thread with its own Data object, so that concurrent reads are possible. As for writes, we can do locking on a static variable. A quick way to do this is using ReentrantReadWriteLock class in JDK1.5.
Just some thoughts. Please don't mind me if this post doesn't make much sense. I just started my assignment 2 days ago, still in the process of analyzing the requirements. Hope you guys can correct me if I'm wrong and lead me to better ideas.
Kang Wang<br />SCJP, SCWCD, SCJD (great thanks to the ranchers)