Pessimistic Autonomous Lock (Java, Spring)

I am trying to implement a pessimistic standalone lock using Spring and JPA / Hibernate. I have a lock table in my database that stores all locks (identifier of a locked record, timestamp and user). The LockManager service interface is as follows:

public interface LockManager {

    @Transactional(isolation=Isolation.SERIALIZABLE)    
    public Boolean TestAndGetLock(Application app, User user);

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

The TestAndGetLock method first checks to see if an existing write lock exists. If there is, it returns true and exits. If it is not, it returns false and creates a lock (writes a new lock to the lock table). Only then does webapp actually start the business transaction (in this case, it displays the edit form for the application passed as a parameter).

Could you tell if this design is correct?

+3
source share
1 answer

I would fix the design:

public boolean lock(Application app, User user);

public void unlock(Application app, User user);

so the names will be more clear. The behavior would be as follows: the client code calls lock (), and if it blocked smth, it returns true, otherwise false. This fixes some of the misunderstandings in your api: if it successfully blocked smth, then why does it return false? In addition, it would be easier to write client code:

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

The second method, in my opinion, is in order.

+1
source

Source: https://habr.com/ru/post/1775841/


All Articles