Hello,
As many developpers working on SJDC, I'm figthing with locks
To prepare myself for this part I have read a lot about
thread, synchronized blocks and new Lock interface in
Java 5.
I have as well read a lot from this forum, especially:
Topic: Clarification on Record Lock without Cookie Topic: locking without cookies Topic: NX: lock/unlock - how to identify clients without lock cookie
But I'm not enough confident with my code and the moreI read about that, the more I get confused...
So at the moment I have the following code (given in ugly pseudo-code, I hope I don't break forum rules). Please have a look and tell me what you think of it.
My Data class is using a LockManager, which is an Object composed of a synchronized Set (with help of java5 ReadWriteLock).
- When a record is lock, its recNo is put on the Set.
- When a record is unLock, its recNo is removed from the Set.
Data class:
public synchronized void lock (int recNo) {
wait while lock is set for recNo;
add recNo into lockManager;
}
public synchronized void unlock(int i) {
remove recNo from lockManager;
signal to waiting thread that lock has been released;
}
lock/unlock are call from Data class when read() and from client when update()/delete().
The whole Data instance is lock when create a new record.
Points that confusing me are:
- is that locking scheme is correct ?
- how to handle special case like a client disconnect while updating...
How to insure the lock/unlock scheme ?
<edit>
after reading again post about locking I figure some problems in my implementation.
I understood I have to:
- always call lock/unlock from client
- use one Data instance per connection with help of a Factory
- use a Map instead of a Set to store locked recNo
- use a mechanism to unlock a deleted record
- handle dead or very slow connection is pretty hard
Now I'm still confused
:
- isn't it dangeous to delegate locking call to client ? What will happen if
a client does direct call to update/delete/read ???
- why should I identify who locks the record (with a cookie or with factored Data instance) ???
- In an older thread I have read about someone who got 100% on lock while having change signature of lock from lock(int recNo) into lock(int recNo, int cookie). Isn't this too hazardous ???
- what if I don't implement the last point (slow or dead connection) ?
</edit>
Thanks you for all comments and advices you may post
[ September 28, 2005: Message edited by: guillaume ame ]