Daniel Rodríguez
Daniel Rodríguez

Reputation: 582

EJB Singleton - Lock READ method calling a Lock WRITE method of the same instance

Given a Singleton like this one:

@Singleton
public class waitingTimeManager {

    private Map<Integer, Object> waitingTimes;

    @PostConstruct
    public void setup() {
        waitingTimes = new HashMap<>();
    }

    @Lock(LockType.READ)
    public boolean shouldWeWait(Integer id) {
        if (waitingTimes.containsKey(id)) {
            boolean wait = someLogic(waitingTimes.get(id));
            if (!wait) {
               // we don't need to wait for it anymore
               stopWaiting(id);
            }
            return wait;
        }
        return false;
    }

    @Lock(LockType.WRITE)
    public void stopWaiting(Integer id){
        waitingTimes.remove(id);
    }

}

The initial method shouldWeWait can be accessed at the same time by several threads. The other stopWaiting will need to get a write lock.

Will the call to stopWaiting inside shouldWeWait try to get a WRITE Lock? or simply execute it as it already got the READ Lock initially?

Upvotes: 1

Views: 884

Answers (1)

user3714601
user3714601

Reputation: 1271

No, it won't try to get write lock.

Container job is done within interceptors, wrapping EJB method calls. For example, when stateless BeanA calls your singleton - it does so through proxy, which makes possible the guarantees given by container (retrieving lock, etc.).

But in this case, it's just a normal method call (stopWaiting), not wrapped by proxy, so no place for magic.

Upvotes: 3

Related Questions