• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Locking/Unlocking code

 
archana kher
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am doing following assumption:
Following way client code will be executed:
a. DbServer dbServer = getAccessToDBServer();
b. Kookie kookie = dbServer.lockRecord(recordNos);
c. dbServer.updateRecord(Data,recordNos,kookie);//update/delete
d. dbServer.unlockRecord(recordNos,kookie);

In other words client needs to call lock/unlock exclusively before performing mutable operations.

Here is the code:

!!!DBServer api's are not synchronized!!!

/**
* Executes record locking protocol. It maintains locking information on record.
*/
public class LockManager {
private HashMap<Long,Kookie> map;
public LockManager() {
}
/**
* Acquires lock over record. If record is not available for locking executing
* thread gives up the CPU till record is available for lock.
* @param recordNos
* @param clientKookie
*/
public void lock(long recordNos,Kookie clientKookie){
Kookie kookie = null;
while(true){//need to wait till lock is acquired
synchronized(map){
if ((kookie = map.get(recordNos)) == null){
clientKookie.setKookieBusy(true);
map.put(recordNos,clientKookie);
return;
}
}
synchronized(kookie){
try {
kookie.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

/**
* Releases lock acquired on passed record.
* @param recordNos
*/
public void unlock(long recordNos){
Kookie kookie = null;
synchronized(map){
kookie = map.get(recordNos);
map.remove(recordNos);
}
synchronized(kookie){
try {
kookie.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

/**
* Checks if record is locked by passed kookie;
* @param recordNos
* @param aKookie
* @return
*/
public boolean isRecordLocked(int recordNos,Kookie aKookie){
synchronized(map){
Kookie kookie = map.get(recordNos);
return aKookie.equals(kookie);
}
}
}

public class DBServer{
...
.
.
public long lockRecord(long recordNos) throws RecordNotFoundException {
Kookie kookie = KookieHolder.reserve(recordNos);
lockManager.acquireLock(recordNos,kookie);
return kookie.kookieValue();
}

public void unlock(long recordNos, long kookie) throws SecurityException {
KookieHolder.unreserve(recordNos,new Kookie(kookie));
lockManager.releaseLock(recordNos);
}
}

'Kookie' is a object on which threads are synchronized. Kookie has longvalue which actually is the kookie value & returned to client.

Friends let me know your thoughts on it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic