开发者

Pessimistic Offline Lock (Java, Spring)

开发者 https://www.devze.com 2023-01-26 11:52 出处:网络
I\'m trying to implement a pessimistic offline lock using Spring and JPA/Hibernate. I have a lock table in my database that stores all locks (id of the record that\'s locked, timestamp and user). The

I'm trying to implement a pessimistic offline lock using Spring and JPA/Hibernate. I have a lock table in my database that stores all locks (id of the record that's locked, timestamp and user). The LockManager service interface looks like this:

public interface LockManager {

    @Transactional(isolation=Isolation.SERIALIZABLE)    
   开发者_运维技巧 public Boolean TestAndGetLock(Application app, User user);

    public void realeaseLock(Application app, User user);
}

The method TestAndGetLock first tests whether there is an existing lock on the record. If there is, it returns true and terminates. If there isn't any, it returns false and creates the lock (writes a new lock in the lock table). Only then does the webapp actually start the business transaction (in this case, it shows an edit form for the application passed as a parameter).

Could you tell me whether this design is correct?


I would correct the design to:

public boolean lock(Application app, User user);

public void unlock(Application app, User user);

so here the names will be more clear. The behaviour would be the following: client code calls lock() and if it locked smth, it returns true, false otherwise. It corrects some misunderstanding in your api: if it sucessfully locked smth, then why it returns false? Also, it would be simplier to write client code:

if (lockManager.lock()) {
...
} else {
   throw new LockNotObtainedException()
}

The second method is ok in my opinion.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号